repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/modules/boto_vpc.py
associate_dhcp_options_to_vpc
python
def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)}
Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1641-L1671
[ "def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None,\n keyid=None, profile=None):\n '''\n Check whether a VPC with the given name or id exists.\n Returns the vpc_id or None. Raises SaltInvocationError if\n both vpc_id and vpc_name are None. Optionally raise a\n CommandExecutionError if the VPC does not exist.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile\n '''\n\n if not _exactly_one((vpc_name, vpc_id)):\n raise SaltInvocationError('One (but not both) of vpc_id or vpc_name '\n 'must be provided.')\n if vpc_name:\n vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid,\n profile=profile)\n elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid,\n profile=profile):\n log.info('VPC %s does not exist.', vpc_id)\n return None\n return vpc_id\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
dhcp_options_exists
python
def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1674-L1697
[ "def resource_exists(resource, name=None, resource_id=None, tags=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n Given a resource type and name, return {exists: true} if it exists,\n {exists: false} if it does not exist, or {error: {message: error text}\n on error.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_vpc.resource_exists internet_gateway myigw\n\n '''\n\n try:\n return {'exists': bool(_find_resources(resource, name=name,\n resource_id=resource_id,\n tags=tags, region=region,\n key=key, keyid=keyid,\n profile=profile))}\n except BotoServerError as e:\n return {'error': __utils__['boto.get_error'](e)}\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
create_network_acl
python
def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r
Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1700-L1757
[ "def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None,\n keyid=None, profile=None):\n '''\n Check whether a VPC with the given name or id exists.\n Returns the vpc_id or None. Raises SaltInvocationError if\n both vpc_id and vpc_name are None. Optionally raise a\n CommandExecutionError if the VPC does not exist.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile\n '''\n\n if not _exactly_one((vpc_name, vpc_id)):\n raise SaltInvocationError('One (but not both) of vpc_id or vpc_name '\n 'must be provided.')\n if vpc_name:\n vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid,\n profile=profile)\n elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid,\n profile=profile):\n log.info('VPC %s does not exist.', vpc_id)\n return None\n return vpc_id\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
delete_network_acl
python
def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile)
Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1760-L1793
[ "def _delete_resource(resource, name=None, resource_id=None, region=None,\n key=None, keyid=None, profile=None, **kwargs):\n '''\n Delete a VPC resource. Returns True if successful, otherwise False.\n '''\n\n if not _exactly_one((name, resource_id)):\n raise SaltInvocationError('One (but not both) of name or id must be '\n 'provided.')\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n delete_resource = getattr(conn, 'delete_' + resource)\n except AttributeError:\n raise AttributeError('{0} function does not exist for boto VPC '\n 'connection.'.format('delete_' + resource))\n if name:\n resource_id = _get_resource_id(resource, name,\n region=region, key=key,\n keyid=keyid, profile=profile)\n if not resource_id:\n return {'deleted': False, 'error': {'message':\n '{0} {1} does not exist.'.format(resource, name)}}\n\n if delete_resource(resource_id, **kwargs):\n _cache_id(name, sub_resource=resource,\n resource_id=resource_id,\n invalidate=True,\n region=region,\n key=key, keyid=keyid,\n profile=profile)\n return {'deleted': True}\n else:\n if name:\n e = '{0} {1} was not deleted.'.format(resource, name)\n else:\n e = '{0} was not deleted.'.format(resource)\n return {'deleted': False, 'error': {'message': e}}\n except BotoServerError as e:\n return {'deleted': False, 'error': __utils__['boto.get_error'](e)}\n", "def _get_resource(resource, name=None, resource_id=None, region=None,\n key=None, keyid=None, profile=None):\n '''\n Get a VPC resource based on resource type and name or id.\n Cache the id if name was provided.\n '''\n\n if not _exactly_one((name, resource_id)):\n raise SaltInvocationError('One (but not both) of name or id must be '\n 'provided.')\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n f = 'get_all_{0}'.format(resource)\n if not f.endswith('s'):\n f = f + 's'\n get_resources = getattr(conn, f)\n filter_parameters = {}\n\n if name:\n filter_parameters['filters'] = {'tag:Name': name}\n if resource_id:\n filter_parameters['{0}_ids'.format(resource)] = resource_id\n\n try:\n r = get_resources(**filter_parameters)\n except BotoServerError as e:\n if e.code.endswith('.NotFound'):\n return None\n raise\n\n if r:\n if len(r) == 1:\n if name:\n _cache_id(name, sub_resource=resource,\n resource_id=r[0].id,\n region=region,\n key=key, keyid=keyid,\n profile=profile)\n return r[0]\n else:\n raise CommandExecutionError('Found more than one '\n '{0} named \"{1}\"'.format(\n resource, name))\n else:\n return None\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
network_acl_exists
python
def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1796-L1819
[ "def resource_exists(resource, name=None, resource_id=None, tags=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n Given a resource type and name, return {exists: true} if it exists,\n {exists: false} if it does not exist, or {error: {message: error text}\n on error.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_vpc.resource_exists internet_gateway myigw\n\n '''\n\n try:\n return {'exists': bool(_find_resources(resource, name=name,\n resource_id=resource_id,\n tags=tags, region=region,\n key=key, keyid=keyid,\n profile=profile))}\n except BotoServerError as e:\n return {'error': __utils__['boto.get_error'](e)}\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
associate_network_acl_to_subnet
python
def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)}
Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1822-L1870
[ "def _get_resource_id(resource, name, region=None, key=None,\n keyid=None, profile=None):\n '''\n Get an AWS id for a VPC resource by type and name.\n '''\n\n _id = _cache_id(name, sub_resource=resource,\n region=region, key=key,\n keyid=keyid, profile=profile)\n if _id:\n return _id\n\n r = _get_resource(resource, name=name, region=region, key=key,\n keyid=keyid, profile=profile)\n\n if r:\n return r.id\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
disassociate_network_acl
python
def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)}
Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1873-L1909
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
create_network_acl_entry
python
def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs)
Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1965-L1983
[ "def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None,\n rule_action=None, cidr_block=None, egress=None,\n network_acl_name=None, icmp_code=None, icmp_type=None,\n port_range_from=None, port_range_to=None, replace=False,\n region=None, key=None, keyid=None, profile=None):\n if replace:\n rkey = 'replaced'\n else:\n rkey = 'created'\n\n if not _exactly_one((network_acl_name, network_acl_id)):\n raise SaltInvocationError('One (but not both) of network_acl_id or '\n 'network_acl_name must be provided.')\n\n for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'):\n if locals()[v] is None:\n raise SaltInvocationError('{0} is required.'.format(v))\n\n if network_acl_name:\n network_acl_id = _get_resource_id('network_acl', network_acl_name,\n region=region, key=key,\n keyid=keyid, profile=profile)\n if not network_acl_id:\n return {rkey: False,\n 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}}\n\n if isinstance(protocol, six.string_types):\n if protocol == 'all':\n protocol = -1\n else:\n try:\n protocol = socket.getprotobyname(protocol)\n except socket.error as e:\n raise SaltInvocationError(e)\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if replace:\n f = conn.replace_network_acl_entry\n else:\n f = conn.create_network_acl_entry\n created = f(network_acl_id, rule_number, protocol, rule_action,\n cidr_block, egress=egress, icmp_code=icmp_code,\n icmp_type=icmp_type, port_range_from=port_range_from,\n port_range_to=port_range_to)\n if created:\n log.info('Network ACL entry was %s', rkey)\n else:\n log.warning('Network ACL entry was not %s', rkey)\n return {rkey: created}\n except BotoServerError as e:\n return {rkey: False, 'error': __utils__['boto.get_error'](e)}\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
delete_network_acl_entry
python
def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)}
Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2008-L2045
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
create_route_table
python
def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile)
Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2048-L2071
[ "def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None,\n keyid=None, profile=None):\n '''\n Check whether a VPC with the given name or id exists.\n Returns the vpc_id or None. Raises SaltInvocationError if\n both vpc_id and vpc_name are None. Optionally raise a\n CommandExecutionError if the VPC does not exist.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile\n '''\n\n if not _exactly_one((vpc_name, vpc_id)):\n raise SaltInvocationError('One (but not both) of vpc_id or vpc_name '\n 'must be provided.')\n if vpc_name:\n vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid,\n profile=profile)\n elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid,\n profile=profile):\n log.info('VPC %s does not exist.', vpc_id)\n return None\n return vpc_id\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
delete_route_table
python
def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile)
Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2074-L2089
[ "def _delete_resource(resource, name=None, resource_id=None, region=None,\n key=None, keyid=None, profile=None, **kwargs):\n '''\n Delete a VPC resource. Returns True if successful, otherwise False.\n '''\n\n if not _exactly_one((name, resource_id)):\n raise SaltInvocationError('One (but not both) of name or id must be '\n 'provided.')\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n delete_resource = getattr(conn, 'delete_' + resource)\n except AttributeError:\n raise AttributeError('{0} function does not exist for boto VPC '\n 'connection.'.format('delete_' + resource))\n if name:\n resource_id = _get_resource_id(resource, name,\n region=region, key=key,\n keyid=keyid, profile=profile)\n if not resource_id:\n return {'deleted': False, 'error': {'message':\n '{0} {1} does not exist.'.format(resource, name)}}\n\n if delete_resource(resource_id, **kwargs):\n _cache_id(name, sub_resource=resource,\n resource_id=resource_id,\n invalidate=True,\n region=region,\n key=key, keyid=keyid,\n profile=profile)\n return {'deleted': True}\n else:\n if name:\n e = '{0} {1} was not deleted.'.format(resource, name)\n else:\n e = '{0} was not deleted.'.format(resource)\n return {'deleted': False, 'error': {'message': e}}\n except BotoServerError as e:\n return {'deleted': False, 'error': __utils__['boto.get_error'](e)}\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
route_table_exists
python
def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2092-L2113
[ "def resource_exists(resource, name=None, resource_id=None, tags=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n Given a resource type and name, return {exists: true} if it exists,\n {exists: false} if it does not exist, or {error: {message: error text}\n on error.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_vpc.resource_exists internet_gateway myigw\n\n '''\n\n try:\n return {'exists': bool(_find_resources(resource, name=name,\n resource_id=resource_id,\n tags=tags, region=region,\n key=key, keyid=keyid,\n profile=profile))}\n except BotoServerError as e:\n return {'error': __utils__['boto.get_error'](e)}\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
route_exists
python
def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2116-L2181
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
associate_route_table
python
def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)}
Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2184-L2233
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
disassociate_route_table
python
def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)}
Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2236-L2260
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
replace_route_table_association
python
def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)}
Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2263-L2282
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
create_route
python
def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2285-L2379
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
delete_route
python
def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile)
Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2382-L2417
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
replace_route
python
def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)}
Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2420-L2468
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
describe_route_table
python
def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2471-L2529
[ "def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
describe_route_tables
python
def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2532-L2615
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
_get_subnet_explicit_route_table
python
def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None
helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2694-L2708
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
request_vpc_peering_connection
python
def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)}
Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2711-L2826
[ "def _vpc_peering_conn_id_for_name(name, conn):\n '''\n Get the ID associated with this name\n '''\n log.debug('Retrieving VPC peering connection id')\n ids = _get_peering_connection_ids(name, conn)\n if not ids:\n ids = [None] # Let callers handle the case where we have no id\n elif len(ids) > 1:\n raise SaltInvocationError('Found multiple VPC peering connections '\n 'with the same name!! '\n 'Please make sure you have only '\n 'one VPC peering connection named {0} '\n 'or invoke this function with a VPC '\n 'peering connection ID'.format(name))\n\n return ids[0]\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
_get_peering_connection_ids
python
def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings]
:param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2829-L2850
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
describe_vpc_peering_connection
python
def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) }
Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2853-L2888
[ "def _get_peering_connection_ids(name, conn):\n '''\n :param name: The name of the VPC peering connection.\n :type name: String\n :param conn: The boto aws ec2 connection.\n :return: The id associated with this peering connection\n\n Returns the VPC peering connection ids\n given the VPC peering connection name.\n '''\n filters = [{\n 'Name': 'tag:Name',\n 'Values': [name],\n }, {\n 'Name': 'status-code',\n 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING],\n }]\n\n peerings = conn.describe_vpc_peering_connections(\n Filters=filters).get('VpcPeeringConnections',\n [])\n return [x['VpcPeeringConnectionId'] for x in peerings]\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
accept_vpc_peering_connection
python
def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)}
Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2891-L2953
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
_vpc_peering_conn_id_for_name
python
def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0]
Get the ID associated with this name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2956-L2972
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
delete_vpc_peering_connection
python
def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e}
Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2975-L3033
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
is_peering_connection_pending
python
def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE
Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L3036-L3094
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
saltstack/salt
salt/modules/boto_vpc.py
peering_connection_pending_from_vpc
python
def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L3097-L3168
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon VPC .. versionadded:: 2014.7.0 :depends: - boto >= 2.8.0 - boto3 >= 1.2.6 :configuration: This module accepts explicit VPC 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 here__. .. __: 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 vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml vpc.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. versionchanged:: 2015.8.0 All methods now return a dictionary. Create and delete methods return: .. code-block:: yaml created: true or .. code-block:: yaml created: false error: message: error message Request methods (e.g., `describe_vpc`) return: .. code-block:: yaml vpcs: - {...} - {...} or .. code-block:: yaml error: message: error message .. versionadded:: 2016.11.0 Functions to request, accept, delete and describe VPC peering connections. Named VPC peering connections can be requested using these modules. VPC owner accounts can accept VPC peering connections (named or otherwise). Examples showing creation of VPC peering connection .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 Check to see if VPC peering connection is pending .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 Accept VPC peering connection .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 Deleting VPC peering connection via this module .. code-block:: bash # Delete a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' # 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 socket import time import random # Import Salt libs import salt.utils.compat import salt.utils.versions from salt.exceptions import SaltInvocationError, CommandExecutionError # from salt.utils import exactly_one # TODO: Uncomment this and s/_exactly_one/exactly_one/ # See note in utils.boto PROVISIONING = 'provisioning' PENDING_ACCEPTANCE = 'pending-acceptance' ACTIVE = 'active' log = logging.getLogger(__name__) # Import third party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error # pylint: disable=import-error try: #pylint: disable=unused-import import boto import botocore import boto.vpc #pylint: enable=unused-import from boto.exception import BotoServerError logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error try: #pylint: disable=unused-import import boto3 #pylint: enable=unused-import logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' # the boto_vpc execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 # the boto_vpc execution module relies on the create_nat_gateway() method # which was added in boto3 1.2.6 return salt.utils.versions.check_boto_reqs( boto_ver='2.8.0', boto3_ver='1.2.6' ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'vpc', pack=__salt__) if HAS_BOTO3: __utils__['boto3.assign_funcs'](__name__, 'ec2', get_conn_funcname='_get_conn3', cache_id_funcname='_cache_id3', exactly_one_funcname=None) def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, find and return matching VPC ids. ''' if all((vpc_id, vpc_name)): raise SaltInvocationError('Only one of vpc_name or vpc_id may be ' 'provided.') if not any((vpc_id, vpc_name, tags, cidr)): raise SaltInvocationError('At least one of the following must be ' 'provided: vpc_id, vpc_name, cidr or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if vpc_name: filter_parameters['filters']['tag:Name'] = vpc_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug('The filters criteria %s matched the following VPCs:%s', filter_parameters, vpcs) if vpcs: return [vpc.id for vpc in vpcs] else: return [] def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)} def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None} def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False} def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)} def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)) def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile) def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile) def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)} def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile) def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile) def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def _create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, replace=False, region=None, key=None, keyid=None, profile=None): if replace: rkey = 'replaced' else: rkey = 'created' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'protocol', 'rule_action', 'cidr_block'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {rkey: False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} if isinstance(protocol, six.string_types): if protocol == 'all': protocol = -1 else: try: protocol = socket.getprotobyname(protocol) except socket.error as e: raise SaltInvocationError(e) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if replace: f = conn.replace_network_acl_entry else: f = conn.create_network_acl_entry created = f(network_acl_id, rule_number, protocol, rule_action, cidr_block, egress=egress, icmp_code=icmp_code, icmp_type=icmp_type, port_range_from=port_range_from, port_range_to=port_range_to) if created: log.info('Network ACL entry was %s', rkey) else: log.warning('Network ACL entry was not %s', rkey) return {rkey: created} except BotoServerError as e: return {rkey: False, 'error': __utils__['boto.get_error'](e)} def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs) def replace_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Replaces a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(replace=True, **kwargs) def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)} def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile) def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile) def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)} def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)} def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile) def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)} def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} def _create_dhcp_options(conn, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None): return conn.create_dhcp_options(domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type) def _maybe_set_name_tag(name, obj): if name: obj.add_tag("Name", name) log.debug('%s is now named as %s', obj, name) def _maybe_set_tags(tags, obj): if tags: # Not all objects in Boto have an 'add_tags()' method. try: obj.add_tags(tags) except AttributeError: for tag, value in tags.items(): obj.add_tag(tag, value) log.debug('The following tags: %s were added to %s', ', '.join(tags), obj) def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames): if dns_support: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support) log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid) if dns_hostnames: conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames) log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid) def _maybe_name_route_table(conn, vpcid, vpc_name): route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid}) if not route_tables: log.warning('no default route table found') return default_table = None for table in route_tables: for association in getattr(table, 'associations', {}): if getattr(association, 'main', False): default_table = table break if not default_table: log.warning('no default route table found') return name = '{0}-default-table'.format(vpc_name) _maybe_set_name_tag(name, default_table) log.debug('Default route table name was set to: %s on vpc %s', name, vpcid) def _key_iter(key, keys, item): elements_list = [] for r_item in getattr(item, key): element = {} for r_key in keys: if hasattr(r_item, r_key): element[r_key] = getattr(r_item, r_key) elements_list.append(element) return elements_list def _key_remap(key, keys, item): elements_list = [] for r_item in item.get(key, []): element = {} for r_outkey, r_inkey in six.iteritems(keys): if r_inkey in r_item: element[r_outkey] = r_item.get(r_inkey) elements_list.append(element) return elements_list def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)} def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings] def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) } def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)} def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0] def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e} def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE
saltstack/salt
salt/utils/botomod.py
cache_id
python
def cache_id(service, name, sub_resource=None, resource_id=None, invalidate=False, region=None, key=None, keyid=None, profile=None): ''' Cache, invalidate, or retrieve an AWS resource id keyed by name. .. code-block:: python __utils__['boto.cache_id']('ec2', 'myinstance', 'i-a1b2c3', profile='custom_profile') ''' cxkey, _, _, _ = _get_profile(service, region, key, keyid, profile) if sub_resource: cxkey = '{0}:{1}:{2}:id'.format(cxkey, sub_resource, name) else: cxkey = '{0}:{1}:id'.format(cxkey, name) if invalidate: if cxkey in __context__: del __context__[cxkey] return True elif resource_id in __context__.values(): ctx = dict((k, v) for k, v in __context__.items() if v != resource_id) __context__.clear() __context__.update(ctx) return True else: return False if resource_id: __context__[cxkey] = resource_id return True return __context__.get(cxkey)
Cache, invalidate, or retrieve an AWS resource id keyed by name. .. code-block:: python __utils__['boto.cache_id']('ec2', 'myinstance', 'i-a1b2c3', profile='custom_profile')
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/botomod.py#L115-L150
[ "def _get_profile(service, region, key, keyid, profile):\n if profile:\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile)\n elif isinstance(profile, dict):\n _profile = profile\n key = _profile.get('key', None)\n keyid = _profile.get('keyid', None)\n region = _profile.get('region', region or None)\n if not region and __salt__['config.option'](service + '.region'):\n region = __salt__['config.option'](service + '.region')\n\n if not region:\n region = 'us-east-1'\n if not key and __salt__['config.option'](service + '.key'):\n key = __salt__['config.option'](service + '.key')\n if not keyid and __salt__['config.option'](service + '.keyid'):\n keyid = __salt__['config.option'](service + '.keyid')\n\n label = 'boto_{0}:'.format(service)\n if keyid:\n hash_string = region + keyid + key\n if six.PY3:\n hash_string = salt.utils.stringutils.to_bytes(hash_string)\n cxkey = label + hashlib.md5(hash_string).hexdigest()\n else:\n cxkey = label + region\n\n return (cxkey, region, key, keyid)\n" ]
# -*- coding: utf-8 -*- ''' Boto Common Utils ================= Note: This module depends on the dicts packed by the loader and, therefore, must be accessed via the loader or from the __utils__ dict. The __utils__ dict will not be automatically available to execution modules until 2015.8.0. The `salt.utils.compat.pack_dunder` helper function provides backwards compatibility. This module provides common functionality for the boto execution modules. The expected usage is to call `assign_funcs` from the `__virtual__` function of the module. This will bring properly initialized partials of `_get_conn` and `_cache_id` into the module's namespace. Example Usage: .. code-block:: python def __virtual__(): # only required in 2015.2 salt.utils.compat.pack_dunder(__name__) __utils__['boto.assign_funcs'](__name__, 'vpc') def test(): conn = _get_conn() vpc_id = _cache_id('test-vpc') .. versionadded:: 2015.8.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import hashlib import logging import sys from functools import partial from salt.loader import minion_mods # Import salt libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.exceptions import SaltInvocationError import salt.utils.stringutils import salt.utils.versions # Import third party libs # pylint: disable=import-error try: # pylint: disable=import-error import boto import boto.exception # pylint: enable=import-error logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error log = logging.getLogger(__name__) __salt__ = None __virtualname__ = 'boto' def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' has_boto_requirements = salt.utils.versions.check_boto_reqs(check_boto3=False) if has_boto_requirements is True: global __salt__ if not __salt__: __salt__ = minion_mods(__opts__) return __virtualname__ return has_boto_requirements def _get_profile(service, region, key, keyid, profile): if profile: if isinstance(profile, six.string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', region or None) if not region and __salt__['config.option'](service + '.region'): region = __salt__['config.option'](service + '.region') if not region: region = 'us-east-1' if not key and __salt__['config.option'](service + '.key'): key = __salt__['config.option'](service + '.key') if not keyid and __salt__['config.option'](service + '.keyid'): keyid = __salt__['config.option'](service + '.keyid') label = 'boto_{0}:'.format(service) if keyid: hash_string = region + keyid + key if six.PY3: hash_string = salt.utils.stringutils.to_bytes(hash_string) cxkey = label + hashlib.md5(hash_string).hexdigest() else: cxkey = label + region return (cxkey, region, key, keyid) def cache_id_func(service): ''' Returns a partial ``cache_id`` function for the provided service. .. code-block:: python cache_id = __utils__['boto.cache_id_func']('ec2') cache_id('myinstance', 'i-a1b2c3') instance_id = cache_id('myinstance') ''' return partial(cache_id, service) def get_connection(service, module=None, region=None, key=None, keyid=None, profile=None): ''' Return a boto connection for the service. .. code-block:: python conn = __utils__['boto.get_connection']('ec2', profile='custom_profile') ''' # future lint: disable=blacklisted-function module = str(module or service) module, submodule = (str('boto.') + module).rsplit(str('.'), 1) # future lint: enable=blacklisted-function svc_mod = getattr(__import__(module, fromlist=[submodule]), submodule) cxkey, region, key, keyid = _get_profile(service, region, key, keyid, profile) cxkey = cxkey + ':conn' if cxkey in __context__: return __context__[cxkey] try: conn = svc_mod.connect_to_region(region, aws_access_key_id=keyid, aws_secret_access_key=key) if conn is None: raise SaltInvocationError('Region "{0}" is not ' 'valid.'.format(region)) except boto.exception.NoAuthHandlerFound: raise SaltInvocationError('No authentication credentials found when ' 'attempting to make boto {0} connection to ' 'region "{1}".'.format(service, region)) __context__[cxkey] = conn return conn def get_connection_func(service, module=None): ''' Returns a partial ``get_connection`` function for the provided service. .. code-block:: python get_conn = __utils__['boto.get_connection_func']('ec2') conn = get_conn() ''' return partial(get_connection, service, module=module) def get_error(e): # The returns from boto modules vary greatly between modules. We need to # assume that none of the data we're looking for exists. aws = {} if hasattr(e, 'status'): aws['status'] = e.status if hasattr(e, 'reason'): aws['reason'] = e.reason if hasattr(e, 'message') and e.message != '': aws['message'] = e.message if hasattr(e, 'error_code') and e.error_code is not None: aws['code'] = e.error_code if 'message' in aws and 'reason' in aws: message = '{0}: {1}'.format(aws['reason'], aws['message']) elif 'message' in aws: message = aws['message'] elif 'reason' in aws: message = aws['reason'] else: message = '' r = {'message': message} if aws: r['aws'] = aws return r def exactly_n(l, n=1): ''' Tests that exactly N items in an iterable are "truthy" (neither None, False, nor 0). ''' i = iter(l) return all(any(i) for j in range(n)) and not any(i) def exactly_one(l): return exactly_n(l) def assign_funcs(modname, service, module=None, pack=None): ''' Assign _get_conn and _cache_id functions to the named module. .. code-block:: python __utils__['boto.assign_partials'](__name__, 'ec2') ''' if pack: global __salt__ # pylint: disable=W0601 __salt__ = pack mod = sys.modules[modname] setattr(mod, '_get_conn', get_connection_func(service, module=module)) setattr(mod, '_cache_id', cache_id_func(service)) # TODO: Remove this and import salt.utils.data.exactly_one into boto_* modules instead # Leaving this way for now so boto modules can be back ported setattr(mod, '_exactly_one', exactly_one) def paged_call(function, *args, **kwargs): ''' Retrieve full set of values from a boto API call that may truncate its results, yielding each page as it is obtained. ''' marker_flag = kwargs.pop('marker_flag', 'marker') marker_arg = kwargs.pop('marker_flag', 'marker') while True: ret = function(*args, **kwargs) marker = ret.get(marker_flag) yield ret if not marker: break kwargs[marker_arg] = marker
saltstack/salt
salt/utils/botomod.py
get_connection
python
def get_connection(service, module=None, region=None, key=None, keyid=None, profile=None): ''' Return a boto connection for the service. .. code-block:: python conn = __utils__['boto.get_connection']('ec2', profile='custom_profile') ''' # future lint: disable=blacklisted-function module = str(module or service) module, submodule = (str('boto.') + module).rsplit(str('.'), 1) # future lint: enable=blacklisted-function svc_mod = getattr(__import__(module, fromlist=[submodule]), submodule) cxkey, region, key, keyid = _get_profile(service, region, key, keyid, profile) cxkey = cxkey + ':conn' if cxkey in __context__: return __context__[cxkey] try: conn = svc_mod.connect_to_region(region, aws_access_key_id=keyid, aws_secret_access_key=key) if conn is None: raise SaltInvocationError('Region "{0}" is not ' 'valid.'.format(region)) except boto.exception.NoAuthHandlerFound: raise SaltInvocationError('No authentication credentials found when ' 'attempting to make boto {0} connection to ' 'region "{1}".'.format(service, region)) __context__[cxkey] = conn return conn
Return a boto connection for the service. .. code-block:: python conn = __utils__['boto.get_connection']('ec2', profile='custom_profile')
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/botomod.py#L166-L201
[ "def _get_profile(service, region, key, keyid, profile):\n if profile:\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile)\n elif isinstance(profile, dict):\n _profile = profile\n key = _profile.get('key', None)\n keyid = _profile.get('keyid', None)\n region = _profile.get('region', region or None)\n if not region and __salt__['config.option'](service + '.region'):\n region = __salt__['config.option'](service + '.region')\n\n if not region:\n region = 'us-east-1'\n if not key and __salt__['config.option'](service + '.key'):\n key = __salt__['config.option'](service + '.key')\n if not keyid and __salt__['config.option'](service + '.keyid'):\n keyid = __salt__['config.option'](service + '.keyid')\n\n label = 'boto_{0}:'.format(service)\n if keyid:\n hash_string = region + keyid + key\n if six.PY3:\n hash_string = salt.utils.stringutils.to_bytes(hash_string)\n cxkey = label + hashlib.md5(hash_string).hexdigest()\n else:\n cxkey = label + region\n\n return (cxkey, region, key, keyid)\n" ]
# -*- coding: utf-8 -*- ''' Boto Common Utils ================= Note: This module depends on the dicts packed by the loader and, therefore, must be accessed via the loader or from the __utils__ dict. The __utils__ dict will not be automatically available to execution modules until 2015.8.0. The `salt.utils.compat.pack_dunder` helper function provides backwards compatibility. This module provides common functionality for the boto execution modules. The expected usage is to call `assign_funcs` from the `__virtual__` function of the module. This will bring properly initialized partials of `_get_conn` and `_cache_id` into the module's namespace. Example Usage: .. code-block:: python def __virtual__(): # only required in 2015.2 salt.utils.compat.pack_dunder(__name__) __utils__['boto.assign_funcs'](__name__, 'vpc') def test(): conn = _get_conn() vpc_id = _cache_id('test-vpc') .. versionadded:: 2015.8.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import hashlib import logging import sys from functools import partial from salt.loader import minion_mods # Import salt libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.exceptions import SaltInvocationError import salt.utils.stringutils import salt.utils.versions # Import third party libs # pylint: disable=import-error try: # pylint: disable=import-error import boto import boto.exception # pylint: enable=import-error logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error log = logging.getLogger(__name__) __salt__ = None __virtualname__ = 'boto' def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' has_boto_requirements = salt.utils.versions.check_boto_reqs(check_boto3=False) if has_boto_requirements is True: global __salt__ if not __salt__: __salt__ = minion_mods(__opts__) return __virtualname__ return has_boto_requirements def _get_profile(service, region, key, keyid, profile): if profile: if isinstance(profile, six.string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', region or None) if not region and __salt__['config.option'](service + '.region'): region = __salt__['config.option'](service + '.region') if not region: region = 'us-east-1' if not key and __salt__['config.option'](service + '.key'): key = __salt__['config.option'](service + '.key') if not keyid and __salt__['config.option'](service + '.keyid'): keyid = __salt__['config.option'](service + '.keyid') label = 'boto_{0}:'.format(service) if keyid: hash_string = region + keyid + key if six.PY3: hash_string = salt.utils.stringutils.to_bytes(hash_string) cxkey = label + hashlib.md5(hash_string).hexdigest() else: cxkey = label + region return (cxkey, region, key, keyid) def cache_id(service, name, sub_resource=None, resource_id=None, invalidate=False, region=None, key=None, keyid=None, profile=None): ''' Cache, invalidate, or retrieve an AWS resource id keyed by name. .. code-block:: python __utils__['boto.cache_id']('ec2', 'myinstance', 'i-a1b2c3', profile='custom_profile') ''' cxkey, _, _, _ = _get_profile(service, region, key, keyid, profile) if sub_resource: cxkey = '{0}:{1}:{2}:id'.format(cxkey, sub_resource, name) else: cxkey = '{0}:{1}:id'.format(cxkey, name) if invalidate: if cxkey in __context__: del __context__[cxkey] return True elif resource_id in __context__.values(): ctx = dict((k, v) for k, v in __context__.items() if v != resource_id) __context__.clear() __context__.update(ctx) return True else: return False if resource_id: __context__[cxkey] = resource_id return True return __context__.get(cxkey) def cache_id_func(service): ''' Returns a partial ``cache_id`` function for the provided service. .. code-block:: python cache_id = __utils__['boto.cache_id_func']('ec2') cache_id('myinstance', 'i-a1b2c3') instance_id = cache_id('myinstance') ''' return partial(cache_id, service) def get_connection_func(service, module=None): ''' Returns a partial ``get_connection`` function for the provided service. .. code-block:: python get_conn = __utils__['boto.get_connection_func']('ec2') conn = get_conn() ''' return partial(get_connection, service, module=module) def get_error(e): # The returns from boto modules vary greatly between modules. We need to # assume that none of the data we're looking for exists. aws = {} if hasattr(e, 'status'): aws['status'] = e.status if hasattr(e, 'reason'): aws['reason'] = e.reason if hasattr(e, 'message') and e.message != '': aws['message'] = e.message if hasattr(e, 'error_code') and e.error_code is not None: aws['code'] = e.error_code if 'message' in aws and 'reason' in aws: message = '{0}: {1}'.format(aws['reason'], aws['message']) elif 'message' in aws: message = aws['message'] elif 'reason' in aws: message = aws['reason'] else: message = '' r = {'message': message} if aws: r['aws'] = aws return r def exactly_n(l, n=1): ''' Tests that exactly N items in an iterable are "truthy" (neither None, False, nor 0). ''' i = iter(l) return all(any(i) for j in range(n)) and not any(i) def exactly_one(l): return exactly_n(l) def assign_funcs(modname, service, module=None, pack=None): ''' Assign _get_conn and _cache_id functions to the named module. .. code-block:: python __utils__['boto.assign_partials'](__name__, 'ec2') ''' if pack: global __salt__ # pylint: disable=W0601 __salt__ = pack mod = sys.modules[modname] setattr(mod, '_get_conn', get_connection_func(service, module=module)) setattr(mod, '_cache_id', cache_id_func(service)) # TODO: Remove this and import salt.utils.data.exactly_one into boto_* modules instead # Leaving this way for now so boto modules can be back ported setattr(mod, '_exactly_one', exactly_one) def paged_call(function, *args, **kwargs): ''' Retrieve full set of values from a boto API call that may truncate its results, yielding each page as it is obtained. ''' marker_flag = kwargs.pop('marker_flag', 'marker') marker_arg = kwargs.pop('marker_flag', 'marker') while True: ret = function(*args, **kwargs) marker = ret.get(marker_flag) yield ret if not marker: break kwargs[marker_arg] = marker
saltstack/salt
salt/utils/botomod.py
exactly_n
python
def exactly_n(l, n=1): ''' Tests that exactly N items in an iterable are "truthy" (neither None, False, nor 0). ''' i = iter(l) return all(any(i) for j in range(n)) and not any(i)
Tests that exactly N items in an iterable are "truthy" (neither None, False, nor 0).
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/botomod.py#L243-L249
null
# -*- coding: utf-8 -*- ''' Boto Common Utils ================= Note: This module depends on the dicts packed by the loader and, therefore, must be accessed via the loader or from the __utils__ dict. The __utils__ dict will not be automatically available to execution modules until 2015.8.0. The `salt.utils.compat.pack_dunder` helper function provides backwards compatibility. This module provides common functionality for the boto execution modules. The expected usage is to call `assign_funcs` from the `__virtual__` function of the module. This will bring properly initialized partials of `_get_conn` and `_cache_id` into the module's namespace. Example Usage: .. code-block:: python def __virtual__(): # only required in 2015.2 salt.utils.compat.pack_dunder(__name__) __utils__['boto.assign_funcs'](__name__, 'vpc') def test(): conn = _get_conn() vpc_id = _cache_id('test-vpc') .. versionadded:: 2015.8.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import hashlib import logging import sys from functools import partial from salt.loader import minion_mods # Import salt libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.exceptions import SaltInvocationError import salt.utils.stringutils import salt.utils.versions # Import third party libs # pylint: disable=import-error try: # pylint: disable=import-error import boto import boto.exception # pylint: enable=import-error logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error log = logging.getLogger(__name__) __salt__ = None __virtualname__ = 'boto' def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' has_boto_requirements = salt.utils.versions.check_boto_reqs(check_boto3=False) if has_boto_requirements is True: global __salt__ if not __salt__: __salt__ = minion_mods(__opts__) return __virtualname__ return has_boto_requirements def _get_profile(service, region, key, keyid, profile): if profile: if isinstance(profile, six.string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', region or None) if not region and __salt__['config.option'](service + '.region'): region = __salt__['config.option'](service + '.region') if not region: region = 'us-east-1' if not key and __salt__['config.option'](service + '.key'): key = __salt__['config.option'](service + '.key') if not keyid and __salt__['config.option'](service + '.keyid'): keyid = __salt__['config.option'](service + '.keyid') label = 'boto_{0}:'.format(service) if keyid: hash_string = region + keyid + key if six.PY3: hash_string = salt.utils.stringutils.to_bytes(hash_string) cxkey = label + hashlib.md5(hash_string).hexdigest() else: cxkey = label + region return (cxkey, region, key, keyid) def cache_id(service, name, sub_resource=None, resource_id=None, invalidate=False, region=None, key=None, keyid=None, profile=None): ''' Cache, invalidate, or retrieve an AWS resource id keyed by name. .. code-block:: python __utils__['boto.cache_id']('ec2', 'myinstance', 'i-a1b2c3', profile='custom_profile') ''' cxkey, _, _, _ = _get_profile(service, region, key, keyid, profile) if sub_resource: cxkey = '{0}:{1}:{2}:id'.format(cxkey, sub_resource, name) else: cxkey = '{0}:{1}:id'.format(cxkey, name) if invalidate: if cxkey in __context__: del __context__[cxkey] return True elif resource_id in __context__.values(): ctx = dict((k, v) for k, v in __context__.items() if v != resource_id) __context__.clear() __context__.update(ctx) return True else: return False if resource_id: __context__[cxkey] = resource_id return True return __context__.get(cxkey) def cache_id_func(service): ''' Returns a partial ``cache_id`` function for the provided service. .. code-block:: python cache_id = __utils__['boto.cache_id_func']('ec2') cache_id('myinstance', 'i-a1b2c3') instance_id = cache_id('myinstance') ''' return partial(cache_id, service) def get_connection(service, module=None, region=None, key=None, keyid=None, profile=None): ''' Return a boto connection for the service. .. code-block:: python conn = __utils__['boto.get_connection']('ec2', profile='custom_profile') ''' # future lint: disable=blacklisted-function module = str(module or service) module, submodule = (str('boto.') + module).rsplit(str('.'), 1) # future lint: enable=blacklisted-function svc_mod = getattr(__import__(module, fromlist=[submodule]), submodule) cxkey, region, key, keyid = _get_profile(service, region, key, keyid, profile) cxkey = cxkey + ':conn' if cxkey in __context__: return __context__[cxkey] try: conn = svc_mod.connect_to_region(region, aws_access_key_id=keyid, aws_secret_access_key=key) if conn is None: raise SaltInvocationError('Region "{0}" is not ' 'valid.'.format(region)) except boto.exception.NoAuthHandlerFound: raise SaltInvocationError('No authentication credentials found when ' 'attempting to make boto {0} connection to ' 'region "{1}".'.format(service, region)) __context__[cxkey] = conn return conn def get_connection_func(service, module=None): ''' Returns a partial ``get_connection`` function for the provided service. .. code-block:: python get_conn = __utils__['boto.get_connection_func']('ec2') conn = get_conn() ''' return partial(get_connection, service, module=module) def get_error(e): # The returns from boto modules vary greatly between modules. We need to # assume that none of the data we're looking for exists. aws = {} if hasattr(e, 'status'): aws['status'] = e.status if hasattr(e, 'reason'): aws['reason'] = e.reason if hasattr(e, 'message') and e.message != '': aws['message'] = e.message if hasattr(e, 'error_code') and e.error_code is not None: aws['code'] = e.error_code if 'message' in aws and 'reason' in aws: message = '{0}: {1}'.format(aws['reason'], aws['message']) elif 'message' in aws: message = aws['message'] elif 'reason' in aws: message = aws['reason'] else: message = '' r = {'message': message} if aws: r['aws'] = aws return r def exactly_one(l): return exactly_n(l) def assign_funcs(modname, service, module=None, pack=None): ''' Assign _get_conn and _cache_id functions to the named module. .. code-block:: python __utils__['boto.assign_partials'](__name__, 'ec2') ''' if pack: global __salt__ # pylint: disable=W0601 __salt__ = pack mod = sys.modules[modname] setattr(mod, '_get_conn', get_connection_func(service, module=module)) setattr(mod, '_cache_id', cache_id_func(service)) # TODO: Remove this and import salt.utils.data.exactly_one into boto_* modules instead # Leaving this way for now so boto modules can be back ported setattr(mod, '_exactly_one', exactly_one) def paged_call(function, *args, **kwargs): ''' Retrieve full set of values from a boto API call that may truncate its results, yielding each page as it is obtained. ''' marker_flag = kwargs.pop('marker_flag', 'marker') marker_arg = kwargs.pop('marker_flag', 'marker') while True: ret = function(*args, **kwargs) marker = ret.get(marker_flag) yield ret if not marker: break kwargs[marker_arg] = marker
saltstack/salt
salt/utils/botomod.py
assign_funcs
python
def assign_funcs(modname, service, module=None, pack=None): ''' Assign _get_conn and _cache_id functions to the named module. .. code-block:: python __utils__['boto.assign_partials'](__name__, 'ec2') ''' if pack: global __salt__ # pylint: disable=W0601 __salt__ = pack mod = sys.modules[modname] setattr(mod, '_get_conn', get_connection_func(service, module=module)) setattr(mod, '_cache_id', cache_id_func(service)) # TODO: Remove this and import salt.utils.data.exactly_one into boto_* modules instead # Leaving this way for now so boto modules can be back ported setattr(mod, '_exactly_one', exactly_one)
Assign _get_conn and _cache_id functions to the named module. .. code-block:: python __utils__['boto.assign_partials'](__name__, 'ec2')
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/botomod.py#L256-L273
[ "def cache_id_func(service):\n '''\n Returns a partial ``cache_id`` function for the provided service.\n\n .. code-block:: python\n\n cache_id = __utils__['boto.cache_id_func']('ec2')\n cache_id('myinstance', 'i-a1b2c3')\n instance_id = cache_id('myinstance')\n '''\n return partial(cache_id, service)\n", "def get_connection_func(service, module=None):\n '''\n Returns a partial ``get_connection`` function for the provided service.\n\n .. code-block:: python\n\n get_conn = __utils__['boto.get_connection_func']('ec2')\n conn = get_conn()\n '''\n return partial(get_connection, service, module=module)\n" ]
# -*- coding: utf-8 -*- ''' Boto Common Utils ================= Note: This module depends on the dicts packed by the loader and, therefore, must be accessed via the loader or from the __utils__ dict. The __utils__ dict will not be automatically available to execution modules until 2015.8.0. The `salt.utils.compat.pack_dunder` helper function provides backwards compatibility. This module provides common functionality for the boto execution modules. The expected usage is to call `assign_funcs` from the `__virtual__` function of the module. This will bring properly initialized partials of `_get_conn` and `_cache_id` into the module's namespace. Example Usage: .. code-block:: python def __virtual__(): # only required in 2015.2 salt.utils.compat.pack_dunder(__name__) __utils__['boto.assign_funcs'](__name__, 'vpc') def test(): conn = _get_conn() vpc_id = _cache_id('test-vpc') .. versionadded:: 2015.8.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import hashlib import logging import sys from functools import partial from salt.loader import minion_mods # Import salt libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.exceptions import SaltInvocationError import salt.utils.stringutils import salt.utils.versions # Import third party libs # pylint: disable=import-error try: # pylint: disable=import-error import boto import boto.exception # pylint: enable=import-error logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error log = logging.getLogger(__name__) __salt__ = None __virtualname__ = 'boto' def __virtual__(): ''' Only load if boto libraries exist and if boto libraries are greater than a given version. ''' has_boto_requirements = salt.utils.versions.check_boto_reqs(check_boto3=False) if has_boto_requirements is True: global __salt__ if not __salt__: __salt__ = minion_mods(__opts__) return __virtualname__ return has_boto_requirements def _get_profile(service, region, key, keyid, profile): if profile: if isinstance(profile, six.string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', region or None) if not region and __salt__['config.option'](service + '.region'): region = __salt__['config.option'](service + '.region') if not region: region = 'us-east-1' if not key and __salt__['config.option'](service + '.key'): key = __salt__['config.option'](service + '.key') if not keyid and __salt__['config.option'](service + '.keyid'): keyid = __salt__['config.option'](service + '.keyid') label = 'boto_{0}:'.format(service) if keyid: hash_string = region + keyid + key if six.PY3: hash_string = salt.utils.stringutils.to_bytes(hash_string) cxkey = label + hashlib.md5(hash_string).hexdigest() else: cxkey = label + region return (cxkey, region, key, keyid) def cache_id(service, name, sub_resource=None, resource_id=None, invalidate=False, region=None, key=None, keyid=None, profile=None): ''' Cache, invalidate, or retrieve an AWS resource id keyed by name. .. code-block:: python __utils__['boto.cache_id']('ec2', 'myinstance', 'i-a1b2c3', profile='custom_profile') ''' cxkey, _, _, _ = _get_profile(service, region, key, keyid, profile) if sub_resource: cxkey = '{0}:{1}:{2}:id'.format(cxkey, sub_resource, name) else: cxkey = '{0}:{1}:id'.format(cxkey, name) if invalidate: if cxkey in __context__: del __context__[cxkey] return True elif resource_id in __context__.values(): ctx = dict((k, v) for k, v in __context__.items() if v != resource_id) __context__.clear() __context__.update(ctx) return True else: return False if resource_id: __context__[cxkey] = resource_id return True return __context__.get(cxkey) def cache_id_func(service): ''' Returns a partial ``cache_id`` function for the provided service. .. code-block:: python cache_id = __utils__['boto.cache_id_func']('ec2') cache_id('myinstance', 'i-a1b2c3') instance_id = cache_id('myinstance') ''' return partial(cache_id, service) def get_connection(service, module=None, region=None, key=None, keyid=None, profile=None): ''' Return a boto connection for the service. .. code-block:: python conn = __utils__['boto.get_connection']('ec2', profile='custom_profile') ''' # future lint: disable=blacklisted-function module = str(module or service) module, submodule = (str('boto.') + module).rsplit(str('.'), 1) # future lint: enable=blacklisted-function svc_mod = getattr(__import__(module, fromlist=[submodule]), submodule) cxkey, region, key, keyid = _get_profile(service, region, key, keyid, profile) cxkey = cxkey + ':conn' if cxkey in __context__: return __context__[cxkey] try: conn = svc_mod.connect_to_region(region, aws_access_key_id=keyid, aws_secret_access_key=key) if conn is None: raise SaltInvocationError('Region "{0}" is not ' 'valid.'.format(region)) except boto.exception.NoAuthHandlerFound: raise SaltInvocationError('No authentication credentials found when ' 'attempting to make boto {0} connection to ' 'region "{1}".'.format(service, region)) __context__[cxkey] = conn return conn def get_connection_func(service, module=None): ''' Returns a partial ``get_connection`` function for the provided service. .. code-block:: python get_conn = __utils__['boto.get_connection_func']('ec2') conn = get_conn() ''' return partial(get_connection, service, module=module) def get_error(e): # The returns from boto modules vary greatly between modules. We need to # assume that none of the data we're looking for exists. aws = {} if hasattr(e, 'status'): aws['status'] = e.status if hasattr(e, 'reason'): aws['reason'] = e.reason if hasattr(e, 'message') and e.message != '': aws['message'] = e.message if hasattr(e, 'error_code') and e.error_code is not None: aws['code'] = e.error_code if 'message' in aws and 'reason' in aws: message = '{0}: {1}'.format(aws['reason'], aws['message']) elif 'message' in aws: message = aws['message'] elif 'reason' in aws: message = aws['reason'] else: message = '' r = {'message': message} if aws: r['aws'] = aws return r def exactly_n(l, n=1): ''' Tests that exactly N items in an iterable are "truthy" (neither None, False, nor 0). ''' i = iter(l) return all(any(i) for j in range(n)) and not any(i) def exactly_one(l): return exactly_n(l) def paged_call(function, *args, **kwargs): ''' Retrieve full set of values from a boto API call that may truncate its results, yielding each page as it is obtained. ''' marker_flag = kwargs.pop('marker_flag', 'marker') marker_arg = kwargs.pop('marker_flag', 'marker') while True: ret = function(*args, **kwargs) marker = ret.get(marker_flag) yield ret if not marker: break kwargs[marker_arg] = marker
saltstack/salt
salt/matchers/ipcidr_match.py
match
python
def match(tgt, opts=None): ''' Matches based on IP address or CIDR notation ''' if not opts: opts = __opts__ try: # Target is an address? tgt = ipaddress.ip_address(tgt) except: # pylint: disable=bare-except try: # Target is a network? tgt = ipaddress.ip_network(tgt) except: # pylint: disable=bare-except log.error('Invalid IP/CIDR target: %s', tgt) return [] proto = 'ipv{0}'.format(tgt.version) grains = opts['grains'] if proto not in grains: match = False elif isinstance(tgt, (ipaddress.IPv4Address, ipaddress.IPv6Address)): match = six.text_type(tgt) in grains[proto] else: match = salt.utils.network.in_subnet(tgt, grains[proto]) return match
Matches based on IP address or CIDR notation
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/ipcidr_match.py#L20-L48
[ "def ip_address(address):\n \"\"\"Take an IP string/int and return an object of the correct type.\n\n Args:\n address: A string or integer, the IP address. Either IPv4 or\n IPv6 addresses may be supplied; integers less than 2**32 will\n be considered to be IPv4 by default.\n\n Returns:\n An IPv4Address or IPv6Address object.\n\n Raises:\n ValueError: if the *address* passed isn't either a v4 or a v6\n address\n\n \"\"\"\n try:\n return IPv4Address(address)\n except (AddressValueError, NetmaskValueError):\n pass\n\n try:\n return IPv6Address(address)\n except (AddressValueError, NetmaskValueError):\n pass\n\n raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %\n address)\n", "def ip_network(address, strict=True):\n \"\"\"Take an IP string/int and return an object of the correct type.\n\n Args:\n address: A string or integer, the IP network. Either IPv4 or\n IPv6 networks may be supplied; integers less than 2**32 will\n be considered to be IPv4 by default.\n\n Returns:\n An IPv4Network or IPv6Network object.\n\n Raises:\n ValueError: if the string passed isn't either a v4 or a v6\n address. Or if the network has host bits set.\n\n \"\"\"\n try:\n return IPv4Network(address, strict)\n except (AddressValueError, NetmaskValueError):\n pass\n\n try:\n return IPv6Network(address, strict)\n except (AddressValueError, NetmaskValueError):\n pass\n\n raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %\n address)\n", "def in_subnet(cidr, addr=None):\n '''\n Returns True if host or (any of) addrs is within specified subnet, otherwise False\n '''\n try:\n cidr = ipaddress.ip_network(cidr)\n except ValueError:\n log.error('Invalid CIDR \\'%s\\'', cidr)\n return False\n\n if addr is None:\n addr = ip_addrs()\n addr.extend(ip_addrs6())\n elif not isinstance(addr, (list, tuple)):\n addr = (addr,)\n\n return any(ipaddress.ip_address(item) in cidr for item in addr)\n" ]
# -*- coding: utf-8 -*- ''' This is the default ipcidr matcher. ''' from __future__ import absolute_import, print_function, unicode_literals import logging from salt.ext import six # pylint: disable=3rd-party-module-not-gated import salt.utils.network # pylint: disable=3rd-party-module-not-gated if six.PY3: import ipaddress else: import salt.ext.ipaddress as ipaddress log = logging.getLogger(__name__)
saltstack/salt
salt/utils/dictupdate.py
update
python
def update(dest, upd, recursive_update=True, merge_lists=False): ''' Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like FunctionWrapper) If merge_lists=True, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behavior is only activated when recursive_update=True. By default merge_lists=False. .. versionchanged: 2016.11.6 When merging lists, duplicate values are removed. Values already present in the ``dest`` list are not added from the ``upd`` list. ''' if (not isinstance(dest, Mapping)) \ or (not isinstance(upd, Mapping)): raise TypeError('Cannot update using non-dict types in dictupdate.update()') updkeys = list(upd.keys()) if not set(list(dest.keys())) & set(updkeys): recursive_update = False if recursive_update: for key in updkeys: val = upd[key] try: dest_subkey = dest.get(key, None) except AttributeError: dest_subkey = None if isinstance(dest_subkey, Mapping) \ and isinstance(val, Mapping): ret = update(dest_subkey, val, merge_lists=merge_lists) dest[key] = ret elif isinstance(dest_subkey, list) and isinstance(val, list): if merge_lists: merged = copy.deepcopy(dest_subkey) merged.extend([x for x in val if x not in merged]) dest[key] = merged else: dest[key] = upd[key] else: dest[key] = upd[key] return dest try: for k in upd: dest[k] = upd[k] except AttributeError: # this mapping is not a dict for k in upd: dest[k] = upd[k] return dest
Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like FunctionWrapper) If merge_lists=True, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behavior is only activated when recursive_update=True. By default merge_lists=False. .. versionchanged: 2016.11.6 When merging lists, duplicate values are removed. Values already present in the ``dest`` list are not added from the ``upd`` list.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L30-L82
null
# -*- coding: utf-8 -*- ''' Alex Martelli's soulution for recursive dict update from http://stackoverflow.com/a/3233356 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals try: from collections.abc import Mapping except ImportError: from collections import Mapping # Import 3rd-party libs import copy import logging # Import salt libs import salt.ext.six as six from salt.defaults import DEFAULT_TARGET_DELIM import salt.utils.data from salt.exceptions import SaltInvocationError from salt.utils.odict import OrderedDict from salt.utils.decorators.jinja import jinja_filter log = logging.getLogger(__name__) def merge_list(obj_a, obj_b): ret = {} for key, val in six.iteritems(obj_a): if key in obj_b: ret[key] = [val, obj_b[key]] else: ret[key] = val return ret def merge_recurse(obj_a, obj_b, merge_lists=False): copied = copy.deepcopy(obj_a) return update(copied, obj_b, merge_lists=merge_lists) def merge_aggregate(obj_a, obj_b): from salt.serializers.yamlex import merge_recursive as _yamlex_merge_recursive return _yamlex_merge_recursive(obj_a, obj_b, level=1) def merge_overwrite(obj_a, obj_b, merge_lists=False): for obj in obj_b: if obj in obj_a: obj_a[obj] = obj_b[obj] return merge_recurse(obj_a, obj_b, merge_lists=merge_lists) def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False): if strategy == 'smart': if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'): strategy = 'aggregate' else: strategy = 'recurse' if strategy == 'list': merged = merge_list(obj_a, obj_b) elif strategy == 'recurse': merged = merge_recurse(obj_a, obj_b, merge_lists) elif strategy == 'aggregate': #: level = 1 merge at least root data merged = merge_aggregate(obj_a, obj_b) elif strategy == 'overwrite': merged = merge_overwrite(obj_a, obj_b, merge_lists) elif strategy == 'none': # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse, # we just do not want to log an error merged = merge_recurse(obj_a, obj_b) else: log.warning( 'Unknown merging strategy \'%s\', fallback to recurse', strategy ) merged = merge_recurse(obj_a, obj_b) return merged def ensure_dict_key( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. ''' if delimiter in keys: a_keys = keys.split(delimiter) else: a_keys = [keys] dict_pointer = in_dict while a_keys: current_key = a_keys.pop(0) if current_key not in dict_pointer or not isinstance(dict_pointer[current_key], dict): dict_pointer[current_key] = OrderedDict() if ordered_dict else {} dict_pointer = dict_pointer[current_key] return in_dict def _dict_rpartition( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return tuple(dict, str) ''' if delimiter in keys: all_but_last_keys, _, last_key = keys.rpartition(delimiter) ensure_dict_key(in_dict, all_but_last_keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer = salt.utils.data.traverse_dict(in_dict, all_but_last_keys, default=None, delimiter=delimiter) else: dict_pointer = in_dict last_key = keys return dict_pointer, last_key @jinja_filter('set_dict_key_value') def set_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also sets whatever is at the end of `in_dict` traversed with `keys` to `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to assign to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer[last_key] = value return in_dict @jinja_filter('update_dict_key_value') def update_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also updates the dict, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to update the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = OrderedDict() if ordered_dict else {} try: dict_pointer[last_key].update(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot update.' ''.format(type(dict_pointer[last_key]))) except (ValueError, TypeError): raise SaltInvocationError('Cannot update {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict @jinja_filter('append_dict_key_value') def append_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `keys`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to append to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].append(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot append.' ''.format(type(dict_pointer[last_key]))) return in_dict @jinja_filter('extend_dict_key_value') def extend_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also extends the list, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to extend the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition( in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].extend(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot extend.' ''.format(type(dict_pointer[last_key]))) except TypeError: raise SaltInvocationError('Cannot extend {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict
saltstack/salt
salt/utils/dictupdate.py
ensure_dict_key
python
def ensure_dict_key( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. ''' if delimiter in keys: a_keys = keys.split(delimiter) else: a_keys = [keys] dict_pointer = in_dict while a_keys: current_key = a_keys.pop(0) if current_key not in dict_pointer or not isinstance(dict_pointer[current_key], dict): dict_pointer[current_key] = OrderedDict() if ordered_dict else {} dict_pointer = dict_pointer[current_key] return in_dict
Ensures that in_dict contains the series of recursive keys defined in keys. :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L142-L166
null
# -*- coding: utf-8 -*- ''' Alex Martelli's soulution for recursive dict update from http://stackoverflow.com/a/3233356 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals try: from collections.abc import Mapping except ImportError: from collections import Mapping # Import 3rd-party libs import copy import logging # Import salt libs import salt.ext.six as six from salt.defaults import DEFAULT_TARGET_DELIM import salt.utils.data from salt.exceptions import SaltInvocationError from salt.utils.odict import OrderedDict from salt.utils.decorators.jinja import jinja_filter log = logging.getLogger(__name__) def update(dest, upd, recursive_update=True, merge_lists=False): ''' Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like FunctionWrapper) If merge_lists=True, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behavior is only activated when recursive_update=True. By default merge_lists=False. .. versionchanged: 2016.11.6 When merging lists, duplicate values are removed. Values already present in the ``dest`` list are not added from the ``upd`` list. ''' if (not isinstance(dest, Mapping)) \ or (not isinstance(upd, Mapping)): raise TypeError('Cannot update using non-dict types in dictupdate.update()') updkeys = list(upd.keys()) if not set(list(dest.keys())) & set(updkeys): recursive_update = False if recursive_update: for key in updkeys: val = upd[key] try: dest_subkey = dest.get(key, None) except AttributeError: dest_subkey = None if isinstance(dest_subkey, Mapping) \ and isinstance(val, Mapping): ret = update(dest_subkey, val, merge_lists=merge_lists) dest[key] = ret elif isinstance(dest_subkey, list) and isinstance(val, list): if merge_lists: merged = copy.deepcopy(dest_subkey) merged.extend([x for x in val if x not in merged]) dest[key] = merged else: dest[key] = upd[key] else: dest[key] = upd[key] return dest try: for k in upd: dest[k] = upd[k] except AttributeError: # this mapping is not a dict for k in upd: dest[k] = upd[k] return dest def merge_list(obj_a, obj_b): ret = {} for key, val in six.iteritems(obj_a): if key in obj_b: ret[key] = [val, obj_b[key]] else: ret[key] = val return ret def merge_recurse(obj_a, obj_b, merge_lists=False): copied = copy.deepcopy(obj_a) return update(copied, obj_b, merge_lists=merge_lists) def merge_aggregate(obj_a, obj_b): from salt.serializers.yamlex import merge_recursive as _yamlex_merge_recursive return _yamlex_merge_recursive(obj_a, obj_b, level=1) def merge_overwrite(obj_a, obj_b, merge_lists=False): for obj in obj_b: if obj in obj_a: obj_a[obj] = obj_b[obj] return merge_recurse(obj_a, obj_b, merge_lists=merge_lists) def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False): if strategy == 'smart': if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'): strategy = 'aggregate' else: strategy = 'recurse' if strategy == 'list': merged = merge_list(obj_a, obj_b) elif strategy == 'recurse': merged = merge_recurse(obj_a, obj_b, merge_lists) elif strategy == 'aggregate': #: level = 1 merge at least root data merged = merge_aggregate(obj_a, obj_b) elif strategy == 'overwrite': merged = merge_overwrite(obj_a, obj_b, merge_lists) elif strategy == 'none': # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse, # we just do not want to log an error merged = merge_recurse(obj_a, obj_b) else: log.warning( 'Unknown merging strategy \'%s\', fallback to recurse', strategy ) merged = merge_recurse(obj_a, obj_b) return merged def _dict_rpartition( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return tuple(dict, str) ''' if delimiter in keys: all_but_last_keys, _, last_key = keys.rpartition(delimiter) ensure_dict_key(in_dict, all_but_last_keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer = salt.utils.data.traverse_dict(in_dict, all_but_last_keys, default=None, delimiter=delimiter) else: dict_pointer = in_dict last_key = keys return dict_pointer, last_key @jinja_filter('set_dict_key_value') def set_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also sets whatever is at the end of `in_dict` traversed with `keys` to `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to assign to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer[last_key] = value return in_dict @jinja_filter('update_dict_key_value') def update_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also updates the dict, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to update the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = OrderedDict() if ordered_dict else {} try: dict_pointer[last_key].update(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot update.' ''.format(type(dict_pointer[last_key]))) except (ValueError, TypeError): raise SaltInvocationError('Cannot update {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict @jinja_filter('append_dict_key_value') def append_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `keys`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to append to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].append(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot append.' ''.format(type(dict_pointer[last_key]))) return in_dict @jinja_filter('extend_dict_key_value') def extend_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also extends the list, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to extend the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition( in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].extend(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot extend.' ''.format(type(dict_pointer[last_key]))) except TypeError: raise SaltInvocationError('Cannot extend {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict
saltstack/salt
salt/utils/dictupdate.py
_dict_rpartition
python
def _dict_rpartition( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return tuple(dict, str) ''' if delimiter in keys: all_but_last_keys, _, last_key = keys.rpartition(delimiter) ensure_dict_key(in_dict, all_but_last_keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer = salt.utils.data.traverse_dict(in_dict, all_but_last_keys, default=None, delimiter=delimiter) else: dict_pointer = in_dict last_key = keys return dict_pointer, last_key
Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return tuple(dict, str)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L169-L200
[ "def traverse_dict(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM):\n '''\n Traverse a dict using a colon-delimited (or otherwise delimited, using the\n 'delimiter' param) target string. The target 'foo:bar:baz' will return\n data['foo']['bar']['baz'] if this value exists, and will otherwise return\n the dict in the default argument.\n '''\n ptr = data\n try:\n for each in key.split(delimiter):\n ptr = ptr[each]\n except (KeyError, IndexError, TypeError):\n # Encountered a non-indexable value in the middle of traversing\n return default\n return ptr\n", "def ensure_dict_key(\n in_dict,\n keys,\n delimiter=DEFAULT_TARGET_DELIM,\n ordered_dict=False):\n '''\n Ensures that in_dict contains the series of recursive keys defined in keys.\n\n :param dict in_dict: The dict to work with.\n :param str keys: The delimited string with one or more keys.\n :param str delimiter: The delimiter to use in `keys`. Defaults to ':'.\n :param bool ordered_dict: Create OrderedDicts if keys are missing.\n Default: create regular dicts.\n '''\n if delimiter in keys:\n a_keys = keys.split(delimiter)\n else:\n a_keys = [keys]\n dict_pointer = in_dict\n while a_keys:\n current_key = a_keys.pop(0)\n if current_key not in dict_pointer or not isinstance(dict_pointer[current_key], dict):\n dict_pointer[current_key] = OrderedDict() if ordered_dict else {}\n dict_pointer = dict_pointer[current_key]\n return in_dict\n" ]
# -*- coding: utf-8 -*- ''' Alex Martelli's soulution for recursive dict update from http://stackoverflow.com/a/3233356 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals try: from collections.abc import Mapping except ImportError: from collections import Mapping # Import 3rd-party libs import copy import logging # Import salt libs import salt.ext.six as six from salt.defaults import DEFAULT_TARGET_DELIM import salt.utils.data from salt.exceptions import SaltInvocationError from salt.utils.odict import OrderedDict from salt.utils.decorators.jinja import jinja_filter log = logging.getLogger(__name__) def update(dest, upd, recursive_update=True, merge_lists=False): ''' Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like FunctionWrapper) If merge_lists=True, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behavior is only activated when recursive_update=True. By default merge_lists=False. .. versionchanged: 2016.11.6 When merging lists, duplicate values are removed. Values already present in the ``dest`` list are not added from the ``upd`` list. ''' if (not isinstance(dest, Mapping)) \ or (not isinstance(upd, Mapping)): raise TypeError('Cannot update using non-dict types in dictupdate.update()') updkeys = list(upd.keys()) if not set(list(dest.keys())) & set(updkeys): recursive_update = False if recursive_update: for key in updkeys: val = upd[key] try: dest_subkey = dest.get(key, None) except AttributeError: dest_subkey = None if isinstance(dest_subkey, Mapping) \ and isinstance(val, Mapping): ret = update(dest_subkey, val, merge_lists=merge_lists) dest[key] = ret elif isinstance(dest_subkey, list) and isinstance(val, list): if merge_lists: merged = copy.deepcopy(dest_subkey) merged.extend([x for x in val if x not in merged]) dest[key] = merged else: dest[key] = upd[key] else: dest[key] = upd[key] return dest try: for k in upd: dest[k] = upd[k] except AttributeError: # this mapping is not a dict for k in upd: dest[k] = upd[k] return dest def merge_list(obj_a, obj_b): ret = {} for key, val in six.iteritems(obj_a): if key in obj_b: ret[key] = [val, obj_b[key]] else: ret[key] = val return ret def merge_recurse(obj_a, obj_b, merge_lists=False): copied = copy.deepcopy(obj_a) return update(copied, obj_b, merge_lists=merge_lists) def merge_aggregate(obj_a, obj_b): from salt.serializers.yamlex import merge_recursive as _yamlex_merge_recursive return _yamlex_merge_recursive(obj_a, obj_b, level=1) def merge_overwrite(obj_a, obj_b, merge_lists=False): for obj in obj_b: if obj in obj_a: obj_a[obj] = obj_b[obj] return merge_recurse(obj_a, obj_b, merge_lists=merge_lists) def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False): if strategy == 'smart': if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'): strategy = 'aggregate' else: strategy = 'recurse' if strategy == 'list': merged = merge_list(obj_a, obj_b) elif strategy == 'recurse': merged = merge_recurse(obj_a, obj_b, merge_lists) elif strategy == 'aggregate': #: level = 1 merge at least root data merged = merge_aggregate(obj_a, obj_b) elif strategy == 'overwrite': merged = merge_overwrite(obj_a, obj_b, merge_lists) elif strategy == 'none': # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse, # we just do not want to log an error merged = merge_recurse(obj_a, obj_b) else: log.warning( 'Unknown merging strategy \'%s\', fallback to recurse', strategy ) merged = merge_recurse(obj_a, obj_b) return merged def ensure_dict_key( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. ''' if delimiter in keys: a_keys = keys.split(delimiter) else: a_keys = [keys] dict_pointer = in_dict while a_keys: current_key = a_keys.pop(0) if current_key not in dict_pointer or not isinstance(dict_pointer[current_key], dict): dict_pointer[current_key] = OrderedDict() if ordered_dict else {} dict_pointer = dict_pointer[current_key] return in_dict @jinja_filter('set_dict_key_value') def set_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also sets whatever is at the end of `in_dict` traversed with `keys` to `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to assign to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer[last_key] = value return in_dict @jinja_filter('update_dict_key_value') def update_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also updates the dict, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to update the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = OrderedDict() if ordered_dict else {} try: dict_pointer[last_key].update(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot update.' ''.format(type(dict_pointer[last_key]))) except (ValueError, TypeError): raise SaltInvocationError('Cannot update {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict @jinja_filter('append_dict_key_value') def append_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `keys`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to append to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].append(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot append.' ''.format(type(dict_pointer[last_key]))) return in_dict @jinja_filter('extend_dict_key_value') def extend_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also extends the list, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to extend the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition( in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].extend(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot extend.' ''.format(type(dict_pointer[last_key]))) except TypeError: raise SaltInvocationError('Cannot extend {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict
saltstack/salt
salt/utils/dictupdate.py
set_dict_key_value
python
def set_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also sets whatever is at the end of `in_dict` traversed with `keys` to `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to assign to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer[last_key] = value return in_dict
Ensures that in_dict contains the series of recursive keys defined in keys. Also sets whatever is at the end of `in_dict` traversed with `keys` to `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to assign to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L204-L228
[ "def _dict_rpartition(\n in_dict,\n keys,\n delimiter=DEFAULT_TARGET_DELIM,\n ordered_dict=False):\n '''\n Helper function to:\n - Ensure all but the last key in `keys` exist recursively in `in_dict`.\n - Return the dict at the one-to-last key, and the last key\n\n :param dict in_dict: The dict to work with.\n :param str keys: The delimited string with one or more keys.\n :param str delimiter: The delimiter to use in `keys`. Defaults to ':'.\n :param bool ordered_dict: Create OrderedDicts if keys are missing.\n Default: create regular dicts.\n\n :return tuple(dict, str)\n '''\n if delimiter in keys:\n all_but_last_keys, _, last_key = keys.rpartition(delimiter)\n ensure_dict_key(in_dict,\n all_but_last_keys,\n delimiter=delimiter,\n ordered_dict=ordered_dict)\n dict_pointer = salt.utils.data.traverse_dict(in_dict,\n all_but_last_keys,\n default=None,\n delimiter=delimiter)\n else:\n dict_pointer = in_dict\n last_key = keys\n return dict_pointer, last_key\n" ]
# -*- coding: utf-8 -*- ''' Alex Martelli's soulution for recursive dict update from http://stackoverflow.com/a/3233356 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals try: from collections.abc import Mapping except ImportError: from collections import Mapping # Import 3rd-party libs import copy import logging # Import salt libs import salt.ext.six as six from salt.defaults import DEFAULT_TARGET_DELIM import salt.utils.data from salt.exceptions import SaltInvocationError from salt.utils.odict import OrderedDict from salt.utils.decorators.jinja import jinja_filter log = logging.getLogger(__name__) def update(dest, upd, recursive_update=True, merge_lists=False): ''' Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like FunctionWrapper) If merge_lists=True, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behavior is only activated when recursive_update=True. By default merge_lists=False. .. versionchanged: 2016.11.6 When merging lists, duplicate values are removed. Values already present in the ``dest`` list are not added from the ``upd`` list. ''' if (not isinstance(dest, Mapping)) \ or (not isinstance(upd, Mapping)): raise TypeError('Cannot update using non-dict types in dictupdate.update()') updkeys = list(upd.keys()) if not set(list(dest.keys())) & set(updkeys): recursive_update = False if recursive_update: for key in updkeys: val = upd[key] try: dest_subkey = dest.get(key, None) except AttributeError: dest_subkey = None if isinstance(dest_subkey, Mapping) \ and isinstance(val, Mapping): ret = update(dest_subkey, val, merge_lists=merge_lists) dest[key] = ret elif isinstance(dest_subkey, list) and isinstance(val, list): if merge_lists: merged = copy.deepcopy(dest_subkey) merged.extend([x for x in val if x not in merged]) dest[key] = merged else: dest[key] = upd[key] else: dest[key] = upd[key] return dest try: for k in upd: dest[k] = upd[k] except AttributeError: # this mapping is not a dict for k in upd: dest[k] = upd[k] return dest def merge_list(obj_a, obj_b): ret = {} for key, val in six.iteritems(obj_a): if key in obj_b: ret[key] = [val, obj_b[key]] else: ret[key] = val return ret def merge_recurse(obj_a, obj_b, merge_lists=False): copied = copy.deepcopy(obj_a) return update(copied, obj_b, merge_lists=merge_lists) def merge_aggregate(obj_a, obj_b): from salt.serializers.yamlex import merge_recursive as _yamlex_merge_recursive return _yamlex_merge_recursive(obj_a, obj_b, level=1) def merge_overwrite(obj_a, obj_b, merge_lists=False): for obj in obj_b: if obj in obj_a: obj_a[obj] = obj_b[obj] return merge_recurse(obj_a, obj_b, merge_lists=merge_lists) def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False): if strategy == 'smart': if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'): strategy = 'aggregate' else: strategy = 'recurse' if strategy == 'list': merged = merge_list(obj_a, obj_b) elif strategy == 'recurse': merged = merge_recurse(obj_a, obj_b, merge_lists) elif strategy == 'aggregate': #: level = 1 merge at least root data merged = merge_aggregate(obj_a, obj_b) elif strategy == 'overwrite': merged = merge_overwrite(obj_a, obj_b, merge_lists) elif strategy == 'none': # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse, # we just do not want to log an error merged = merge_recurse(obj_a, obj_b) else: log.warning( 'Unknown merging strategy \'%s\', fallback to recurse', strategy ) merged = merge_recurse(obj_a, obj_b) return merged def ensure_dict_key( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. ''' if delimiter in keys: a_keys = keys.split(delimiter) else: a_keys = [keys] dict_pointer = in_dict while a_keys: current_key = a_keys.pop(0) if current_key not in dict_pointer or not isinstance(dict_pointer[current_key], dict): dict_pointer[current_key] = OrderedDict() if ordered_dict else {} dict_pointer = dict_pointer[current_key] return in_dict def _dict_rpartition( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return tuple(dict, str) ''' if delimiter in keys: all_but_last_keys, _, last_key = keys.rpartition(delimiter) ensure_dict_key(in_dict, all_but_last_keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer = salt.utils.data.traverse_dict(in_dict, all_but_last_keys, default=None, delimiter=delimiter) else: dict_pointer = in_dict last_key = keys return dict_pointer, last_key @jinja_filter('set_dict_key_value') @jinja_filter('update_dict_key_value') def update_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also updates the dict, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to update the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = OrderedDict() if ordered_dict else {} try: dict_pointer[last_key].update(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot update.' ''.format(type(dict_pointer[last_key]))) except (ValueError, TypeError): raise SaltInvocationError('Cannot update {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict @jinja_filter('append_dict_key_value') def append_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `keys`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to append to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].append(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot append.' ''.format(type(dict_pointer[last_key]))) return in_dict @jinja_filter('extend_dict_key_value') def extend_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also extends the list, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to extend the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition( in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].extend(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot extend.' ''.format(type(dict_pointer[last_key]))) except TypeError: raise SaltInvocationError('Cannot extend {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict
saltstack/salt
salt/utils/dictupdate.py
update_dict_key_value
python
def update_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also updates the dict, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to update the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = OrderedDict() if ordered_dict else {} try: dict_pointer[last_key].update(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot update.' ''.format(type(dict_pointer[last_key]))) except (ValueError, TypeError): raise SaltInvocationError('Cannot update {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict
Ensures that in_dict contains the series of recursive keys defined in keys. Also updates the dict, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to update the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L232-L266
[ "def _dict_rpartition(\n in_dict,\n keys,\n delimiter=DEFAULT_TARGET_DELIM,\n ordered_dict=False):\n '''\n Helper function to:\n - Ensure all but the last key in `keys` exist recursively in `in_dict`.\n - Return the dict at the one-to-last key, and the last key\n\n :param dict in_dict: The dict to work with.\n :param str keys: The delimited string with one or more keys.\n :param str delimiter: The delimiter to use in `keys`. Defaults to ':'.\n :param bool ordered_dict: Create OrderedDicts if keys are missing.\n Default: create regular dicts.\n\n :return tuple(dict, str)\n '''\n if delimiter in keys:\n all_but_last_keys, _, last_key = keys.rpartition(delimiter)\n ensure_dict_key(in_dict,\n all_but_last_keys,\n delimiter=delimiter,\n ordered_dict=ordered_dict)\n dict_pointer = salt.utils.data.traverse_dict(in_dict,\n all_but_last_keys,\n default=None,\n delimiter=delimiter)\n else:\n dict_pointer = in_dict\n last_key = keys\n return dict_pointer, last_key\n" ]
# -*- coding: utf-8 -*- ''' Alex Martelli's soulution for recursive dict update from http://stackoverflow.com/a/3233356 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals try: from collections.abc import Mapping except ImportError: from collections import Mapping # Import 3rd-party libs import copy import logging # Import salt libs import salt.ext.six as six from salt.defaults import DEFAULT_TARGET_DELIM import salt.utils.data from salt.exceptions import SaltInvocationError from salt.utils.odict import OrderedDict from salt.utils.decorators.jinja import jinja_filter log = logging.getLogger(__name__) def update(dest, upd, recursive_update=True, merge_lists=False): ''' Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like FunctionWrapper) If merge_lists=True, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behavior is only activated when recursive_update=True. By default merge_lists=False. .. versionchanged: 2016.11.6 When merging lists, duplicate values are removed. Values already present in the ``dest`` list are not added from the ``upd`` list. ''' if (not isinstance(dest, Mapping)) \ or (not isinstance(upd, Mapping)): raise TypeError('Cannot update using non-dict types in dictupdate.update()') updkeys = list(upd.keys()) if not set(list(dest.keys())) & set(updkeys): recursive_update = False if recursive_update: for key in updkeys: val = upd[key] try: dest_subkey = dest.get(key, None) except AttributeError: dest_subkey = None if isinstance(dest_subkey, Mapping) \ and isinstance(val, Mapping): ret = update(dest_subkey, val, merge_lists=merge_lists) dest[key] = ret elif isinstance(dest_subkey, list) and isinstance(val, list): if merge_lists: merged = copy.deepcopy(dest_subkey) merged.extend([x for x in val if x not in merged]) dest[key] = merged else: dest[key] = upd[key] else: dest[key] = upd[key] return dest try: for k in upd: dest[k] = upd[k] except AttributeError: # this mapping is not a dict for k in upd: dest[k] = upd[k] return dest def merge_list(obj_a, obj_b): ret = {} for key, val in six.iteritems(obj_a): if key in obj_b: ret[key] = [val, obj_b[key]] else: ret[key] = val return ret def merge_recurse(obj_a, obj_b, merge_lists=False): copied = copy.deepcopy(obj_a) return update(copied, obj_b, merge_lists=merge_lists) def merge_aggregate(obj_a, obj_b): from salt.serializers.yamlex import merge_recursive as _yamlex_merge_recursive return _yamlex_merge_recursive(obj_a, obj_b, level=1) def merge_overwrite(obj_a, obj_b, merge_lists=False): for obj in obj_b: if obj in obj_a: obj_a[obj] = obj_b[obj] return merge_recurse(obj_a, obj_b, merge_lists=merge_lists) def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False): if strategy == 'smart': if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'): strategy = 'aggregate' else: strategy = 'recurse' if strategy == 'list': merged = merge_list(obj_a, obj_b) elif strategy == 'recurse': merged = merge_recurse(obj_a, obj_b, merge_lists) elif strategy == 'aggregate': #: level = 1 merge at least root data merged = merge_aggregate(obj_a, obj_b) elif strategy == 'overwrite': merged = merge_overwrite(obj_a, obj_b, merge_lists) elif strategy == 'none': # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse, # we just do not want to log an error merged = merge_recurse(obj_a, obj_b) else: log.warning( 'Unknown merging strategy \'%s\', fallback to recurse', strategy ) merged = merge_recurse(obj_a, obj_b) return merged def ensure_dict_key( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. ''' if delimiter in keys: a_keys = keys.split(delimiter) else: a_keys = [keys] dict_pointer = in_dict while a_keys: current_key = a_keys.pop(0) if current_key not in dict_pointer or not isinstance(dict_pointer[current_key], dict): dict_pointer[current_key] = OrderedDict() if ordered_dict else {} dict_pointer = dict_pointer[current_key] return in_dict def _dict_rpartition( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return tuple(dict, str) ''' if delimiter in keys: all_but_last_keys, _, last_key = keys.rpartition(delimiter) ensure_dict_key(in_dict, all_but_last_keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer = salt.utils.data.traverse_dict(in_dict, all_but_last_keys, default=None, delimiter=delimiter) else: dict_pointer = in_dict last_key = keys return dict_pointer, last_key @jinja_filter('set_dict_key_value') def set_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also sets whatever is at the end of `in_dict` traversed with `keys` to `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to assign to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer[last_key] = value return in_dict @jinja_filter('update_dict_key_value') @jinja_filter('append_dict_key_value') def append_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `keys`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to append to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].append(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot append.' ''.format(type(dict_pointer[last_key]))) return in_dict @jinja_filter('extend_dict_key_value') def extend_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also extends the list, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to extend the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition( in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].extend(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot extend.' ''.format(type(dict_pointer[last_key]))) except TypeError: raise SaltInvocationError('Cannot extend {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict
saltstack/salt
salt/utils/dictupdate.py
append_dict_key_value
python
def append_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `keys`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to append to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].append(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot append.' ''.format(type(dict_pointer[last_key]))) return in_dict
Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `keys`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to append to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L270-L301
[ "def _dict_rpartition(\n in_dict,\n keys,\n delimiter=DEFAULT_TARGET_DELIM,\n ordered_dict=False):\n '''\n Helper function to:\n - Ensure all but the last key in `keys` exist recursively in `in_dict`.\n - Return the dict at the one-to-last key, and the last key\n\n :param dict in_dict: The dict to work with.\n :param str keys: The delimited string with one or more keys.\n :param str delimiter: The delimiter to use in `keys`. Defaults to ':'.\n :param bool ordered_dict: Create OrderedDicts if keys are missing.\n Default: create regular dicts.\n\n :return tuple(dict, str)\n '''\n if delimiter in keys:\n all_but_last_keys, _, last_key = keys.rpartition(delimiter)\n ensure_dict_key(in_dict,\n all_but_last_keys,\n delimiter=delimiter,\n ordered_dict=ordered_dict)\n dict_pointer = salt.utils.data.traverse_dict(in_dict,\n all_but_last_keys,\n default=None,\n delimiter=delimiter)\n else:\n dict_pointer = in_dict\n last_key = keys\n return dict_pointer, last_key\n" ]
# -*- coding: utf-8 -*- ''' Alex Martelli's soulution for recursive dict update from http://stackoverflow.com/a/3233356 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals try: from collections.abc import Mapping except ImportError: from collections import Mapping # Import 3rd-party libs import copy import logging # Import salt libs import salt.ext.six as six from salt.defaults import DEFAULT_TARGET_DELIM import salt.utils.data from salt.exceptions import SaltInvocationError from salt.utils.odict import OrderedDict from salt.utils.decorators.jinja import jinja_filter log = logging.getLogger(__name__) def update(dest, upd, recursive_update=True, merge_lists=False): ''' Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like FunctionWrapper) If merge_lists=True, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behavior is only activated when recursive_update=True. By default merge_lists=False. .. versionchanged: 2016.11.6 When merging lists, duplicate values are removed. Values already present in the ``dest`` list are not added from the ``upd`` list. ''' if (not isinstance(dest, Mapping)) \ or (not isinstance(upd, Mapping)): raise TypeError('Cannot update using non-dict types in dictupdate.update()') updkeys = list(upd.keys()) if not set(list(dest.keys())) & set(updkeys): recursive_update = False if recursive_update: for key in updkeys: val = upd[key] try: dest_subkey = dest.get(key, None) except AttributeError: dest_subkey = None if isinstance(dest_subkey, Mapping) \ and isinstance(val, Mapping): ret = update(dest_subkey, val, merge_lists=merge_lists) dest[key] = ret elif isinstance(dest_subkey, list) and isinstance(val, list): if merge_lists: merged = copy.deepcopy(dest_subkey) merged.extend([x for x in val if x not in merged]) dest[key] = merged else: dest[key] = upd[key] else: dest[key] = upd[key] return dest try: for k in upd: dest[k] = upd[k] except AttributeError: # this mapping is not a dict for k in upd: dest[k] = upd[k] return dest def merge_list(obj_a, obj_b): ret = {} for key, val in six.iteritems(obj_a): if key in obj_b: ret[key] = [val, obj_b[key]] else: ret[key] = val return ret def merge_recurse(obj_a, obj_b, merge_lists=False): copied = copy.deepcopy(obj_a) return update(copied, obj_b, merge_lists=merge_lists) def merge_aggregate(obj_a, obj_b): from salt.serializers.yamlex import merge_recursive as _yamlex_merge_recursive return _yamlex_merge_recursive(obj_a, obj_b, level=1) def merge_overwrite(obj_a, obj_b, merge_lists=False): for obj in obj_b: if obj in obj_a: obj_a[obj] = obj_b[obj] return merge_recurse(obj_a, obj_b, merge_lists=merge_lists) def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False): if strategy == 'smart': if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'): strategy = 'aggregate' else: strategy = 'recurse' if strategy == 'list': merged = merge_list(obj_a, obj_b) elif strategy == 'recurse': merged = merge_recurse(obj_a, obj_b, merge_lists) elif strategy == 'aggregate': #: level = 1 merge at least root data merged = merge_aggregate(obj_a, obj_b) elif strategy == 'overwrite': merged = merge_overwrite(obj_a, obj_b, merge_lists) elif strategy == 'none': # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse, # we just do not want to log an error merged = merge_recurse(obj_a, obj_b) else: log.warning( 'Unknown merging strategy \'%s\', fallback to recurse', strategy ) merged = merge_recurse(obj_a, obj_b) return merged def ensure_dict_key( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. ''' if delimiter in keys: a_keys = keys.split(delimiter) else: a_keys = [keys] dict_pointer = in_dict while a_keys: current_key = a_keys.pop(0) if current_key not in dict_pointer or not isinstance(dict_pointer[current_key], dict): dict_pointer[current_key] = OrderedDict() if ordered_dict else {} dict_pointer = dict_pointer[current_key] return in_dict def _dict_rpartition( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return tuple(dict, str) ''' if delimiter in keys: all_but_last_keys, _, last_key = keys.rpartition(delimiter) ensure_dict_key(in_dict, all_but_last_keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer = salt.utils.data.traverse_dict(in_dict, all_but_last_keys, default=None, delimiter=delimiter) else: dict_pointer = in_dict last_key = keys return dict_pointer, last_key @jinja_filter('set_dict_key_value') def set_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also sets whatever is at the end of `in_dict` traversed with `keys` to `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to assign to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer[last_key] = value return in_dict @jinja_filter('update_dict_key_value') def update_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also updates the dict, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to update the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = OrderedDict() if ordered_dict else {} try: dict_pointer[last_key].update(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot update.' ''.format(type(dict_pointer[last_key]))) except (ValueError, TypeError): raise SaltInvocationError('Cannot update {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict @jinja_filter('append_dict_key_value') @jinja_filter('extend_dict_key_value') def extend_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also extends the list, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to extend the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition( in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].extend(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot extend.' ''.format(type(dict_pointer[last_key]))) except TypeError: raise SaltInvocationError('Cannot extend {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict
saltstack/salt
salt/utils/dictupdate.py
extend_dict_key_value
python
def extend_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also extends the list, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to extend the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition( in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].extend(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot extend.' ''.format(type(dict_pointer[last_key]))) except TypeError: raise SaltInvocationError('Cannot extend {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict
Ensures that in_dict contains the series of recursive keys defined in keys. Also extends the list, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to extend the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L305-L340
[ "def _dict_rpartition(\n in_dict,\n keys,\n delimiter=DEFAULT_TARGET_DELIM,\n ordered_dict=False):\n '''\n Helper function to:\n - Ensure all but the last key in `keys` exist recursively in `in_dict`.\n - Return the dict at the one-to-last key, and the last key\n\n :param dict in_dict: The dict to work with.\n :param str keys: The delimited string with one or more keys.\n :param str delimiter: The delimiter to use in `keys`. Defaults to ':'.\n :param bool ordered_dict: Create OrderedDicts if keys are missing.\n Default: create regular dicts.\n\n :return tuple(dict, str)\n '''\n if delimiter in keys:\n all_but_last_keys, _, last_key = keys.rpartition(delimiter)\n ensure_dict_key(in_dict,\n all_but_last_keys,\n delimiter=delimiter,\n ordered_dict=ordered_dict)\n dict_pointer = salt.utils.data.traverse_dict(in_dict,\n all_but_last_keys,\n default=None,\n delimiter=delimiter)\n else:\n dict_pointer = in_dict\n last_key = keys\n return dict_pointer, last_key\n" ]
# -*- coding: utf-8 -*- ''' Alex Martelli's soulution for recursive dict update from http://stackoverflow.com/a/3233356 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals try: from collections.abc import Mapping except ImportError: from collections import Mapping # Import 3rd-party libs import copy import logging # Import salt libs import salt.ext.six as six from salt.defaults import DEFAULT_TARGET_DELIM import salt.utils.data from salt.exceptions import SaltInvocationError from salt.utils.odict import OrderedDict from salt.utils.decorators.jinja import jinja_filter log = logging.getLogger(__name__) def update(dest, upd, recursive_update=True, merge_lists=False): ''' Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like FunctionWrapper) If merge_lists=True, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behavior is only activated when recursive_update=True. By default merge_lists=False. .. versionchanged: 2016.11.6 When merging lists, duplicate values are removed. Values already present in the ``dest`` list are not added from the ``upd`` list. ''' if (not isinstance(dest, Mapping)) \ or (not isinstance(upd, Mapping)): raise TypeError('Cannot update using non-dict types in dictupdate.update()') updkeys = list(upd.keys()) if not set(list(dest.keys())) & set(updkeys): recursive_update = False if recursive_update: for key in updkeys: val = upd[key] try: dest_subkey = dest.get(key, None) except AttributeError: dest_subkey = None if isinstance(dest_subkey, Mapping) \ and isinstance(val, Mapping): ret = update(dest_subkey, val, merge_lists=merge_lists) dest[key] = ret elif isinstance(dest_subkey, list) and isinstance(val, list): if merge_lists: merged = copy.deepcopy(dest_subkey) merged.extend([x for x in val if x not in merged]) dest[key] = merged else: dest[key] = upd[key] else: dest[key] = upd[key] return dest try: for k in upd: dest[k] = upd[k] except AttributeError: # this mapping is not a dict for k in upd: dest[k] = upd[k] return dest def merge_list(obj_a, obj_b): ret = {} for key, val in six.iteritems(obj_a): if key in obj_b: ret[key] = [val, obj_b[key]] else: ret[key] = val return ret def merge_recurse(obj_a, obj_b, merge_lists=False): copied = copy.deepcopy(obj_a) return update(copied, obj_b, merge_lists=merge_lists) def merge_aggregate(obj_a, obj_b): from salt.serializers.yamlex import merge_recursive as _yamlex_merge_recursive return _yamlex_merge_recursive(obj_a, obj_b, level=1) def merge_overwrite(obj_a, obj_b, merge_lists=False): for obj in obj_b: if obj in obj_a: obj_a[obj] = obj_b[obj] return merge_recurse(obj_a, obj_b, merge_lists=merge_lists) def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False): if strategy == 'smart': if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'): strategy = 'aggregate' else: strategy = 'recurse' if strategy == 'list': merged = merge_list(obj_a, obj_b) elif strategy == 'recurse': merged = merge_recurse(obj_a, obj_b, merge_lists) elif strategy == 'aggregate': #: level = 1 merge at least root data merged = merge_aggregate(obj_a, obj_b) elif strategy == 'overwrite': merged = merge_overwrite(obj_a, obj_b, merge_lists) elif strategy == 'none': # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse, # we just do not want to log an error merged = merge_recurse(obj_a, obj_b) else: log.warning( 'Unknown merging strategy \'%s\', fallback to recurse', strategy ) merged = merge_recurse(obj_a, obj_b) return merged def ensure_dict_key( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. ''' if delimiter in keys: a_keys = keys.split(delimiter) else: a_keys = [keys] dict_pointer = in_dict while a_keys: current_key = a_keys.pop(0) if current_key not in dict_pointer or not isinstance(dict_pointer[current_key], dict): dict_pointer[current_key] = OrderedDict() if ordered_dict else {} dict_pointer = dict_pointer[current_key] return in_dict def _dict_rpartition( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return tuple(dict, str) ''' if delimiter in keys: all_but_last_keys, _, last_key = keys.rpartition(delimiter) ensure_dict_key(in_dict, all_but_last_keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer = salt.utils.data.traverse_dict(in_dict, all_but_last_keys, default=None, delimiter=delimiter) else: dict_pointer = in_dict last_key = keys return dict_pointer, last_key @jinja_filter('set_dict_key_value') def set_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also sets whatever is at the end of `in_dict` traversed with `keys` to `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to assign to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer[last_key] = value return in_dict @jinja_filter('update_dict_key_value') def update_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also updates the dict, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to update the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = OrderedDict() if ordered_dict else {} try: dict_pointer[last_key].update(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot update.' ''.format(type(dict_pointer[last_key]))) except (ValueError, TypeError): raise SaltInvocationError('Cannot update {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict @jinja_filter('append_dict_key_value') def append_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `keys`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to append to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].append(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot append.' ''.format(type(dict_pointer[last_key]))) return in_dict @jinja_filter('extend_dict_key_value')
saltstack/salt
salt/cli/batch.py
get_bnum
python
def get_bnum(opts, minions, quiet): ''' Return the active number of minions to maintain ''' partition = lambda x: float(x) / 100.0 * len(minions) try: if '%' in opts['batch']: res = partition(float(opts['batch'].strip('%'))) if res < 1: return int(math.ceil(res)) else: return int(res) else: return int(opts['batch']) except ValueError: if not quiet: salt.utils.stringutils.print_cli('Invalid batch data sent: {0}\nData must be in the ' 'form of %10, 10% or 3'.format(opts['batch']))
Return the active number of minions to maintain
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/batch.py#L29-L46
[ "def print_cli(msg, retries=10, step=0.01):\n '''\n Wrapper around print() that suppresses tracebacks on broken pipes (i.e.\n when salt output is piped to less and less is stopped prematurely).\n '''\n while retries:\n try:\n try:\n print(msg)\n except UnicodeEncodeError:\n print(msg.encode('utf-8'))\n except IOError as exc:\n err = \"{0}\".format(exc)\n if exc.errno != errno.EPIPE:\n if (\n (\"temporarily unavailable\" in err or\n exc.errno in (errno.EAGAIN,)) and\n retries\n ):\n time.sleep(step)\n retries -= 1\n continue\n else:\n raise\n break\n", "partition = lambda x: float(x) / 100.0 * len(minions)\n" ]
# -*- coding: utf-8 -*- ''' Execute batch runs ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import math import time import copy from datetime import datetime, timedelta # Import salt libs import salt.utils.stringutils import salt.client import salt.output import salt.exceptions # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range # pylint: enable=import-error,no-name-in-module,redefined-builtin import logging log = logging.getLogger(__name__) def batch_get_opts( tgt, fun, batch, parent_opts, arg=(), tgt_type='glob', ret='', kwarg=None, **kwargs): # We need to re-import salt.utils.args here # even though it has already been imported. # when cmd_batch is called via the NetAPI # the module is unavailable. import salt.utils.args arg = salt.utils.args.condition_input(arg, kwarg) opts = {'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type, 'ret': ret, 'batch': batch, 'failhard': kwargs.get('failhard', False), 'raw': kwargs.get('raw', False)} if 'timeout' in kwargs: opts['timeout'] = kwargs['timeout'] if 'gather_job_timeout' in kwargs: opts['gather_job_timeout'] = kwargs['gather_job_timeout'] if 'batch_wait' in kwargs: opts['batch_wait'] = int(kwargs['batch_wait']) for key, val in six.iteritems(parent_opts): if key not in opts: opts[key] = val return opts def batch_get_eauth(kwargs): eauth = {} if 'eauth' in kwargs: eauth['eauth'] = kwargs.pop('eauth') if 'username' in kwargs: eauth['username'] = kwargs.pop('username') if 'password' in kwargs: eauth['password'] = kwargs.pop('password') if 'token' in kwargs: eauth['token'] = kwargs.pop('token') return eauth class Batch(object): ''' Manage the execution of batch runs ''' def __init__(self, opts, eauth=None, quiet=False, parser=None): self.opts = opts self.eauth = eauth if eauth else {} self.pub_kwargs = eauth if eauth else {} self.quiet = quiet self.local = salt.client.get_local_client(opts['conf_file']) self.minions, self.ping_gen, self.down_minions = self.__gather_minions() self.options = parser def __gather_minions(self): ''' Return a list of minions to use for the batch run ''' args = [self.opts['tgt'], 'test.ping', [], self.opts['timeout'], ] selected_target_option = self.opts.get('selected_target_option', None) if selected_target_option is not None: args.append(selected_target_option) else: args.append(self.opts.get('tgt_type', 'glob')) self.pub_kwargs['yield_pub_data'] = True ping_gen = self.local.cmd_iter(*args, gather_job_timeout=self.opts['gather_job_timeout'], **self.pub_kwargs) # Broadcast to targets fret = set() nret = set() for ret in ping_gen: if ('minions' and 'jid') in ret: for minion in ret['minions']: nret.add(minion) continue else: try: m = next(six.iterkeys(ret)) except StopIteration: if not self.quiet: salt.utils.stringutils.print_cli('No minions matched the target.') break if m is not None: fret.add(m) return (list(fret), ping_gen, nret.difference(fret)) def get_bnum(self): return get_bnum(self.opts, self.minions, self.quiet) def __update_wait(self, wait): now = datetime.now() i = 0 while i < len(wait) and wait[i] <= now: i += 1 if i: del wait[:i] def run(self): ''' Execute the batch run ''' args = [[], self.opts['fun'], self.opts['arg'], self.opts['timeout'], 'list', ] bnum = self.get_bnum() # No targets to run if not self.minions: return to_run = copy.deepcopy(self.minions) active = [] ret = {} iters = [] # wait the specified time before decide a job is actually done bwait = self.opts.get('batch_wait', 0) wait = [] if self.options: show_jid = self.options.show_jid show_verbose = self.options.verbose else: show_jid = False show_verbose = False # the minion tracker keeps track of responses and iterators # - it removes finished iterators from iters[] # - if a previously detected minion does not respond, its # added with an empty answer to ret{} once the timeout is reached # - unresponsive minions are removed from active[] to make # sure that the main while loop finishes even with unresp minions minion_tracker = {} if not self.quiet: # We already know some minions didn't respond to the ping, so inform # the user we won't be attempting to run a job on them for down_minion in self.down_minions: salt.utils.stringutils.print_cli('Minion {0} did not respond. No job will be sent.'.format(down_minion)) # Iterate while we still have things to execute while len(ret) < len(self.minions): next_ = [] if bwait and wait: self.__update_wait(wait) if len(to_run) <= bnum - len(wait) and not active: # last bit of them, add them all to next iterator while to_run: next_.append(to_run.pop()) else: for i in range(bnum - len(active) - len(wait)): if to_run: minion_id = to_run.pop() if isinstance(minion_id, dict): next_.append(minion_id.keys()[0]) else: next_.append(minion_id) active += next_ args[0] = next_ if next_: if not self.quiet: salt.utils.stringutils.print_cli('\nExecuting run on {0}\n'.format(sorted(next_))) # create a new iterator for this batch of minions new_iter = self.local.cmd_iter_no_block( *args, raw=self.opts.get('raw', False), ret=self.opts.get('return', ''), show_jid=show_jid, verbose=show_verbose, gather_job_timeout=self.opts['gather_job_timeout'], **self.eauth) # add it to our iterators and to the minion_tracker iters.append(new_iter) minion_tracker[new_iter] = {} # every iterator added is 'active' and has its set of minions minion_tracker[new_iter]['minions'] = next_ minion_tracker[new_iter]['active'] = True else: time.sleep(0.02) parts = {} # see if we found more minions for ping_ret in self.ping_gen: if ping_ret is None: break m = next(six.iterkeys(ping_ret)) if m not in self.minions: self.minions.append(m) to_run.append(m) for queue in iters: try: # Gather returns until we get to the bottom ncnt = 0 while True: part = next(queue) if part is None: time.sleep(0.01) ncnt += 1 if ncnt > 5: break continue if self.opts.get('raw'): parts.update({part['data']['id']: part}) if part['data']['id'] in minion_tracker[queue]['minions']: minion_tracker[queue]['minions'].remove(part['data']['id']) else: salt.utils.stringutils.print_cli('minion {0} was already deleted from tracker, probably a duplicate key'.format(part['id'])) else: parts.update(part) for id in part: if id in minion_tracker[queue]['minions']: minion_tracker[queue]['minions'].remove(id) else: salt.utils.stringutils.print_cli('minion {0} was already deleted from tracker, probably a duplicate key'.format(id)) except StopIteration: # if a iterator is done: # - set it to inactive # - add minions that have not responded to parts{} # check if the tracker contains the iterator if queue in minion_tracker: minion_tracker[queue]['active'] = False # add all minions that belong to this iterator and # that have not responded to parts{} with an empty response for minion in minion_tracker[queue]['minions']: if minion not in parts: parts[minion] = {} parts[minion]['ret'] = {} for minion, data in six.iteritems(parts): if minion in active: active.remove(minion) if bwait: wait.append(datetime.now() + timedelta(seconds=bwait)) # Munge retcode into return data failhard = False if 'retcode' in data and isinstance(data['ret'], dict) and 'retcode' not in data['ret']: data['ret']['retcode'] = data['retcode'] if self.opts.get('failhard') and data['ret']['retcode'] > 0: failhard = True if self.opts.get('raw'): ret[minion] = data yield data else: ret[minion] = data['ret'] yield {minion: data['ret']} if not self.quiet: ret[minion] = data['ret'] data[minion] = data.pop('ret') if 'out' in data: out = data.pop('out') else: out = None salt.output.display_output( data, out, self.opts) if failhard: log.error( 'Minion %s returned with non-zero exit code. ' 'Batch run stopped due to failhard', minion ) raise StopIteration # remove inactive iterators from the iters list for queue in minion_tracker: # only remove inactive queues if not minion_tracker[queue]['active'] and queue in iters: iters.remove(queue) # also remove the iterator's minions from the active list for minion in minion_tracker[queue]['minions']: if minion in active: active.remove(minion) if bwait: wait.append(datetime.now() + timedelta(seconds=bwait))
saltstack/salt
salt/cli/batch.py
Batch.__gather_minions
python
def __gather_minions(self): ''' Return a list of minions to use for the batch run ''' args = [self.opts['tgt'], 'test.ping', [], self.opts['timeout'], ] selected_target_option = self.opts.get('selected_target_option', None) if selected_target_option is not None: args.append(selected_target_option) else: args.append(self.opts.get('tgt_type', 'glob')) self.pub_kwargs['yield_pub_data'] = True ping_gen = self.local.cmd_iter(*args, gather_job_timeout=self.opts['gather_job_timeout'], **self.pub_kwargs) # Broadcast to targets fret = set() nret = set() for ret in ping_gen: if ('minions' and 'jid') in ret: for minion in ret['minions']: nret.add(minion) continue else: try: m = next(six.iterkeys(ret)) except StopIteration: if not self.quiet: salt.utils.stringutils.print_cli('No minions matched the target.') break if m is not None: fret.add(m) return (list(fret), ping_gen, nret.difference(fret))
Return a list of minions to use for the batch run
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/batch.py#L115-L153
[ "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n", "def print_cli(msg, retries=10, step=0.01):\n '''\n Wrapper around print() that suppresses tracebacks on broken pipes (i.e.\n when salt output is piped to less and less is stopped prematurely).\n '''\n while retries:\n try:\n try:\n print(msg)\n except UnicodeEncodeError:\n print(msg.encode('utf-8'))\n except IOError as exc:\n err = \"{0}\".format(exc)\n if exc.errno != errno.EPIPE:\n if (\n (\"temporarily unavailable\" in err or\n exc.errno in (errno.EAGAIN,)) and\n retries\n ):\n time.sleep(step)\n retries -= 1\n continue\n else:\n raise\n break\n", "def cmd_iter(\n self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n ret='',\n kwarg=None,\n **kwargs):\n '''\n Yields the individual minion returns as they come in\n\n The function signature is the same as :py:meth:`cmd` with the\n following exceptions.\n\n Normally :py:meth:`cmd_iter` does not yield results for minions that\n are not connected. If you want it to return results for disconnected\n minions set `expect_minions=True` in `kwargs`.\n\n :return: A generator yielding the individual minion returns\n\n .. code-block:: python\n\n >>> ret = local.cmd_iter('*', 'test.ping')\n >>> for i in ret:\n ... print(i)\n {'jerry': {'ret': True}}\n {'dave': {'ret': True}}\n {'stewart': {'ret': True}}\n '''\n was_listening = self.event.cpub\n\n try:\n pub_data = self.run_job(\n tgt,\n fun,\n arg,\n tgt_type,\n ret,\n timeout,\n kwarg=kwarg,\n listen=True,\n **kwargs)\n\n if not pub_data:\n yield pub_data\n else:\n if kwargs.get('yield_pub_data'):\n yield pub_data\n for fn_ret in self.get_iter_returns(pub_data['jid'],\n pub_data['minions'],\n timeout=self._get_timeout(timeout),\n tgt=tgt,\n tgt_type=tgt_type,\n **kwargs):\n if not fn_ret:\n continue\n yield fn_ret\n self._clean_up_subscriptions(pub_data['jid'])\n finally:\n if not was_listening:\n self.event.close_pub()\n" ]
class Batch(object): ''' Manage the execution of batch runs ''' def __init__(self, opts, eauth=None, quiet=False, parser=None): self.opts = opts self.eauth = eauth if eauth else {} self.pub_kwargs = eauth if eauth else {} self.quiet = quiet self.local = salt.client.get_local_client(opts['conf_file']) self.minions, self.ping_gen, self.down_minions = self.__gather_minions() self.options = parser def get_bnum(self): return get_bnum(self.opts, self.minions, self.quiet) def __update_wait(self, wait): now = datetime.now() i = 0 while i < len(wait) and wait[i] <= now: i += 1 if i: del wait[:i] def run(self): ''' Execute the batch run ''' args = [[], self.opts['fun'], self.opts['arg'], self.opts['timeout'], 'list', ] bnum = self.get_bnum() # No targets to run if not self.minions: return to_run = copy.deepcopy(self.minions) active = [] ret = {} iters = [] # wait the specified time before decide a job is actually done bwait = self.opts.get('batch_wait', 0) wait = [] if self.options: show_jid = self.options.show_jid show_verbose = self.options.verbose else: show_jid = False show_verbose = False # the minion tracker keeps track of responses and iterators # - it removes finished iterators from iters[] # - if a previously detected minion does not respond, its # added with an empty answer to ret{} once the timeout is reached # - unresponsive minions are removed from active[] to make # sure that the main while loop finishes even with unresp minions minion_tracker = {} if not self.quiet: # We already know some minions didn't respond to the ping, so inform # the user we won't be attempting to run a job on them for down_minion in self.down_minions: salt.utils.stringutils.print_cli('Minion {0} did not respond. No job will be sent.'.format(down_minion)) # Iterate while we still have things to execute while len(ret) < len(self.minions): next_ = [] if bwait and wait: self.__update_wait(wait) if len(to_run) <= bnum - len(wait) and not active: # last bit of them, add them all to next iterator while to_run: next_.append(to_run.pop()) else: for i in range(bnum - len(active) - len(wait)): if to_run: minion_id = to_run.pop() if isinstance(minion_id, dict): next_.append(minion_id.keys()[0]) else: next_.append(minion_id) active += next_ args[0] = next_ if next_: if not self.quiet: salt.utils.stringutils.print_cli('\nExecuting run on {0}\n'.format(sorted(next_))) # create a new iterator for this batch of minions new_iter = self.local.cmd_iter_no_block( *args, raw=self.opts.get('raw', False), ret=self.opts.get('return', ''), show_jid=show_jid, verbose=show_verbose, gather_job_timeout=self.opts['gather_job_timeout'], **self.eauth) # add it to our iterators and to the minion_tracker iters.append(new_iter) minion_tracker[new_iter] = {} # every iterator added is 'active' and has its set of minions minion_tracker[new_iter]['minions'] = next_ minion_tracker[new_iter]['active'] = True else: time.sleep(0.02) parts = {} # see if we found more minions for ping_ret in self.ping_gen: if ping_ret is None: break m = next(six.iterkeys(ping_ret)) if m not in self.minions: self.minions.append(m) to_run.append(m) for queue in iters: try: # Gather returns until we get to the bottom ncnt = 0 while True: part = next(queue) if part is None: time.sleep(0.01) ncnt += 1 if ncnt > 5: break continue if self.opts.get('raw'): parts.update({part['data']['id']: part}) if part['data']['id'] in minion_tracker[queue]['minions']: minion_tracker[queue]['minions'].remove(part['data']['id']) else: salt.utils.stringutils.print_cli('minion {0} was already deleted from tracker, probably a duplicate key'.format(part['id'])) else: parts.update(part) for id in part: if id in minion_tracker[queue]['minions']: minion_tracker[queue]['minions'].remove(id) else: salt.utils.stringutils.print_cli('minion {0} was already deleted from tracker, probably a duplicate key'.format(id)) except StopIteration: # if a iterator is done: # - set it to inactive # - add minions that have not responded to parts{} # check if the tracker contains the iterator if queue in minion_tracker: minion_tracker[queue]['active'] = False # add all minions that belong to this iterator and # that have not responded to parts{} with an empty response for minion in minion_tracker[queue]['minions']: if minion not in parts: parts[minion] = {} parts[minion]['ret'] = {} for minion, data in six.iteritems(parts): if minion in active: active.remove(minion) if bwait: wait.append(datetime.now() + timedelta(seconds=bwait)) # Munge retcode into return data failhard = False if 'retcode' in data and isinstance(data['ret'], dict) and 'retcode' not in data['ret']: data['ret']['retcode'] = data['retcode'] if self.opts.get('failhard') and data['ret']['retcode'] > 0: failhard = True if self.opts.get('raw'): ret[minion] = data yield data else: ret[minion] = data['ret'] yield {minion: data['ret']} if not self.quiet: ret[minion] = data['ret'] data[minion] = data.pop('ret') if 'out' in data: out = data.pop('out') else: out = None salt.output.display_output( data, out, self.opts) if failhard: log.error( 'Minion %s returned with non-zero exit code. ' 'Batch run stopped due to failhard', minion ) raise StopIteration # remove inactive iterators from the iters list for queue in minion_tracker: # only remove inactive queues if not minion_tracker[queue]['active'] and queue in iters: iters.remove(queue) # also remove the iterator's minions from the active list for minion in minion_tracker[queue]['minions']: if minion in active: active.remove(minion) if bwait: wait.append(datetime.now() + timedelta(seconds=bwait))
saltstack/salt
salt/cli/batch.py
Batch.run
python
def run(self): ''' Execute the batch run ''' args = [[], self.opts['fun'], self.opts['arg'], self.opts['timeout'], 'list', ] bnum = self.get_bnum() # No targets to run if not self.minions: return to_run = copy.deepcopy(self.minions) active = [] ret = {} iters = [] # wait the specified time before decide a job is actually done bwait = self.opts.get('batch_wait', 0) wait = [] if self.options: show_jid = self.options.show_jid show_verbose = self.options.verbose else: show_jid = False show_verbose = False # the minion tracker keeps track of responses and iterators # - it removes finished iterators from iters[] # - if a previously detected minion does not respond, its # added with an empty answer to ret{} once the timeout is reached # - unresponsive minions are removed from active[] to make # sure that the main while loop finishes even with unresp minions minion_tracker = {} if not self.quiet: # We already know some minions didn't respond to the ping, so inform # the user we won't be attempting to run a job on them for down_minion in self.down_minions: salt.utils.stringutils.print_cli('Minion {0} did not respond. No job will be sent.'.format(down_minion)) # Iterate while we still have things to execute while len(ret) < len(self.minions): next_ = [] if bwait and wait: self.__update_wait(wait) if len(to_run) <= bnum - len(wait) and not active: # last bit of them, add them all to next iterator while to_run: next_.append(to_run.pop()) else: for i in range(bnum - len(active) - len(wait)): if to_run: minion_id = to_run.pop() if isinstance(minion_id, dict): next_.append(minion_id.keys()[0]) else: next_.append(minion_id) active += next_ args[0] = next_ if next_: if not self.quiet: salt.utils.stringutils.print_cli('\nExecuting run on {0}\n'.format(sorted(next_))) # create a new iterator for this batch of minions new_iter = self.local.cmd_iter_no_block( *args, raw=self.opts.get('raw', False), ret=self.opts.get('return', ''), show_jid=show_jid, verbose=show_verbose, gather_job_timeout=self.opts['gather_job_timeout'], **self.eauth) # add it to our iterators and to the minion_tracker iters.append(new_iter) minion_tracker[new_iter] = {} # every iterator added is 'active' and has its set of minions minion_tracker[new_iter]['minions'] = next_ minion_tracker[new_iter]['active'] = True else: time.sleep(0.02) parts = {} # see if we found more minions for ping_ret in self.ping_gen: if ping_ret is None: break m = next(six.iterkeys(ping_ret)) if m not in self.minions: self.minions.append(m) to_run.append(m) for queue in iters: try: # Gather returns until we get to the bottom ncnt = 0 while True: part = next(queue) if part is None: time.sleep(0.01) ncnt += 1 if ncnt > 5: break continue if self.opts.get('raw'): parts.update({part['data']['id']: part}) if part['data']['id'] in minion_tracker[queue]['minions']: minion_tracker[queue]['minions'].remove(part['data']['id']) else: salt.utils.stringutils.print_cli('minion {0} was already deleted from tracker, probably a duplicate key'.format(part['id'])) else: parts.update(part) for id in part: if id in minion_tracker[queue]['minions']: minion_tracker[queue]['minions'].remove(id) else: salt.utils.stringutils.print_cli('minion {0} was already deleted from tracker, probably a duplicate key'.format(id)) except StopIteration: # if a iterator is done: # - set it to inactive # - add minions that have not responded to parts{} # check if the tracker contains the iterator if queue in minion_tracker: minion_tracker[queue]['active'] = False # add all minions that belong to this iterator and # that have not responded to parts{} with an empty response for minion in minion_tracker[queue]['minions']: if minion not in parts: parts[minion] = {} parts[minion]['ret'] = {} for minion, data in six.iteritems(parts): if minion in active: active.remove(minion) if bwait: wait.append(datetime.now() + timedelta(seconds=bwait)) # Munge retcode into return data failhard = False if 'retcode' in data and isinstance(data['ret'], dict) and 'retcode' not in data['ret']: data['ret']['retcode'] = data['retcode'] if self.opts.get('failhard') and data['ret']['retcode'] > 0: failhard = True if self.opts.get('raw'): ret[minion] = data yield data else: ret[minion] = data['ret'] yield {minion: data['ret']} if not self.quiet: ret[minion] = data['ret'] data[minion] = data.pop('ret') if 'out' in data: out = data.pop('out') else: out = None salt.output.display_output( data, out, self.opts) if failhard: log.error( 'Minion %s returned with non-zero exit code. ' 'Batch run stopped due to failhard', minion ) raise StopIteration # remove inactive iterators from the iters list for queue in minion_tracker: # only remove inactive queues if not minion_tracker[queue]['active'] and queue in iters: iters.remove(queue) # also remove the iterator's minions from the active list for minion in minion_tracker[queue]['minions']: if minion in active: active.remove(minion) if bwait: wait.append(datetime.now() + timedelta(seconds=bwait))
Execute the batch run
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/batch.py#L166-L349
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n", "def display_output(data, out=None, opts=None, **kwargs):\n '''\n Print the passed data using the desired output\n '''\n if opts is None:\n opts = {}\n display_data = try_printout(data, out, opts, **kwargs)\n\n output_filename = opts.get('output_file', None)\n log.trace('data = %s', data)\n try:\n # output filename can be either '' or None\n if output_filename:\n if not hasattr(output_filename, 'write'):\n ofh = salt.utils.files.fopen(output_filename, 'a') # pylint: disable=resource-leakage\n fh_opened = True\n else:\n # Filehandle/file-like object\n ofh = output_filename\n fh_opened = False\n\n try:\n fdata = display_data\n if isinstance(fdata, six.text_type):\n try:\n fdata = fdata.encode('utf-8')\n except (UnicodeDecodeError, UnicodeEncodeError):\n # try to let the stream write\n # even if we didn't encode it\n pass\n if fdata:\n ofh.write(salt.utils.stringutils.to_str(fdata))\n ofh.write('\\n')\n finally:\n if fh_opened:\n ofh.close()\n return\n if display_data:\n salt.utils.stringutils.print_cli(display_data)\n except IOError as exc:\n # Only raise if it's NOT a broken pipe\n if exc.errno != errno.EPIPE:\n raise exc\n", "def print_cli(msg, retries=10, step=0.01):\n '''\n Wrapper around print() that suppresses tracebacks on broken pipes (i.e.\n when salt output is piped to less and less is stopped prematurely).\n '''\n while retries:\n try:\n try:\n print(msg)\n except UnicodeEncodeError:\n print(msg.encode('utf-8'))\n except IOError as exc:\n err = \"{0}\".format(exc)\n if exc.errno != errno.EPIPE:\n if (\n (\"temporarily unavailable\" in err or\n exc.errno in (errno.EAGAIN,)) and\n retries\n ):\n time.sleep(step)\n retries -= 1\n continue\n else:\n raise\n break\n", "def get_bnum(self):\n return get_bnum(self.opts, self.minions, self.quiet)\n", "def __update_wait(self, wait):\n now = datetime.now()\n i = 0\n while i < len(wait) and wait[i] <= now:\n i += 1\n if i:\n del wait[:i]\n" ]
class Batch(object): ''' Manage the execution of batch runs ''' def __init__(self, opts, eauth=None, quiet=False, parser=None): self.opts = opts self.eauth = eauth if eauth else {} self.pub_kwargs = eauth if eauth else {} self.quiet = quiet self.local = salt.client.get_local_client(opts['conf_file']) self.minions, self.ping_gen, self.down_minions = self.__gather_minions() self.options = parser def __gather_minions(self): ''' Return a list of minions to use for the batch run ''' args = [self.opts['tgt'], 'test.ping', [], self.opts['timeout'], ] selected_target_option = self.opts.get('selected_target_option', None) if selected_target_option is not None: args.append(selected_target_option) else: args.append(self.opts.get('tgt_type', 'glob')) self.pub_kwargs['yield_pub_data'] = True ping_gen = self.local.cmd_iter(*args, gather_job_timeout=self.opts['gather_job_timeout'], **self.pub_kwargs) # Broadcast to targets fret = set() nret = set() for ret in ping_gen: if ('minions' and 'jid') in ret: for minion in ret['minions']: nret.add(minion) continue else: try: m = next(six.iterkeys(ret)) except StopIteration: if not self.quiet: salt.utils.stringutils.print_cli('No minions matched the target.') break if m is not None: fret.add(m) return (list(fret), ping_gen, nret.difference(fret)) def get_bnum(self): return get_bnum(self.opts, self.minions, self.quiet) def __update_wait(self, wait): now = datetime.now() i = 0 while i < len(wait) and wait[i] <= now: i += 1 if i: del wait[:i]
saltstack/salt
salt/modules/dummyproxy_service.py
status
python
def status(name, sig=None): ''' Return the status for a service via dummy, returns a bool whether the service is running. .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' proxy_fn = 'dummy.service_status' resp = __proxy__[proxy_fn](name) if resp['comment'] == 'stopped': return False if resp['comment'] == 'running': return True
Return the status for a service via dummy, returns a bool whether the service is running. .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.status <service name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dummyproxy_service.py#L127-L146
null
# -*- coding: utf-8 -*- ''' Provide the service module for the dummy proxy used in integration tests ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list' } # Define the module's virtual name __virtualname__ = 'service' def __virtual__(): ''' Only work on systems that are a proxy minion ''' try: if salt.utils.platform.is_proxy() \ and __opts__['proxy']['proxytype'] == 'dummy': return __virtualname__ except KeyError: return ( False, 'The dummyproxy_service execution module failed to load. Check ' 'the proxy key in pillar or /etc/salt/proxy.' ) return ( False, 'The dummyproxy_service execution module failed to load: only works ' 'on the integration testsuite dummy proxy minion.' ) def get_all(): ''' Return a list of all available services .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.get_all ''' proxy_fn = 'dummy.service_list' return __proxy__[proxy_fn]() def list_(): ''' Return a list of all available services. .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.list ''' return get_all() def start(name, sig=None): ''' Start the specified service on the dummy .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' proxy_fn = 'dummy.service_start' return __proxy__[proxy_fn](name) def stop(name, sig=None): ''' Stop the specified service on the dummy .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' proxy_fn = 'dummy.service_stop' return __proxy__[proxy_fn](name) def restart(name, sig=None): ''' Restart the specified service with dummy. .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' proxy_fn = 'dummy.service_restart' return __proxy__[proxy_fn](name) def running(name, sig=None): ''' Return whether this service is running. .. versionadded:: 2016.11.3 ''' return status(name).get(name, False) def enabled(name, sig=None): ''' Only the 'redbull' service is 'enabled' in the test .. versionadded:: 2016.11.3 ''' return name == 'redbull'
saltstack/salt
salt/states/xmpp.py
send_msg
python
def send_msg(name, recipient, profile): ''' Send a message to an XMPP user .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipient: admins@xmpp.example.com/salt name The message to send to the XMPP user ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __opts__['test']: ret['comment'] = 'Need to send message to {0}: {1}'.format( recipient, name, ) return ret __salt__['xmpp.send_msg_multi']( message=name, recipients=[recipient], profile=profile, ) ret['result'] = True ret['comment'] = 'Sent message to {0}: {1}'.format(recipient, name) return ret
Send a message to an XMPP user .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipient: admins@xmpp.example.com/salt name The message to send to the XMPP user
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/xmpp.py#L31-L63
null
# -*- coding: utf-8 -*- ''' Sending Messages over XMPP ========================== .. versionadded:: 2014.1.0 This state is useful for firing messages during state runs, using the XMPP protocol .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipient: admins@xmpp.example.com/salt ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): ''' Only load if the XMPP module is available in __salt__ ''' return 'xmpp' if 'xmpp.send_msg' in __salt__ else False def send_msg_multi(name, profile, recipients=None, rooms=None): ''' Send a message to an list of recipients or rooms .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipients: - admins@xmpp.example.com/salt - rooms: - qa@conference.xmpp.example.com name The message to send to the XMPP user ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if recipients is None and rooms is None: ret['comment'] = "Recipients and rooms are empty, no need to send" return ret comment = '' if recipients: comment += ' users {0}'.format(recipients) if rooms: comment += ' rooms {0}'.format(rooms) comment += ', message: {0}'.format(name) if __opts__['test']: ret['comment'] = 'Need to send' + comment return ret __salt__['xmpp.send_msg_multi']( message=name, recipients=recipients, rooms=rooms, profile=profile, ) ret['result'] = True ret['comment'] = 'Sent message to' + comment return ret
saltstack/salt
salt/states/xmpp.py
send_msg_multi
python
def send_msg_multi(name, profile, recipients=None, rooms=None): ''' Send a message to an list of recipients or rooms .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipients: - admins@xmpp.example.com/salt - rooms: - qa@conference.xmpp.example.com name The message to send to the XMPP user ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if recipients is None and rooms is None: ret['comment'] = "Recipients and rooms are empty, no need to send" return ret comment = '' if recipients: comment += ' users {0}'.format(recipients) if rooms: comment += ' rooms {0}'.format(rooms) comment += ', message: {0}'.format(name) if __opts__['test']: ret['comment'] = 'Need to send' + comment return ret __salt__['xmpp.send_msg_multi']( message=name, recipients=recipients, rooms=rooms, profile=profile, ) ret['result'] = True ret['comment'] = 'Sent message to' + comment return ret
Send a message to an list of recipients or rooms .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipients: - admins@xmpp.example.com/salt - rooms: - qa@conference.xmpp.example.com name The message to send to the XMPP user
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/xmpp.py#L66-L116
null
# -*- coding: utf-8 -*- ''' Sending Messages over XMPP ========================== .. versionadded:: 2014.1.0 This state is useful for firing messages during state runs, using the XMPP protocol .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipient: admins@xmpp.example.com/salt ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): ''' Only load if the XMPP module is available in __salt__ ''' return 'xmpp' if 'xmpp.send_msg' in __salt__ else False def send_msg(name, recipient, profile): ''' Send a message to an XMPP user .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipient: admins@xmpp.example.com/salt name The message to send to the XMPP user ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __opts__['test']: ret['comment'] = 'Need to send message to {0}: {1}'.format( recipient, name, ) return ret __salt__['xmpp.send_msg_multi']( message=name, recipients=[recipient], profile=profile, ) ret['result'] = True ret['comment'] = 'Sent message to {0}: {1}'.format(recipient, name) return ret
saltstack/salt
salt/states/libcloud_dns.py
zone_present
python
def zone_present(domain, type, profile): ''' Ensures a record is present. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param type: Zone type (master / slave), defaults to master :type type: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) if not type: type = 'master' matching_zone = [z for z in zones if z['domain'] == domain] if matching_zone: return state_result(True, 'Zone already exists', domain) else: result = __salt__['libcloud_dns.create_zone'](domain, profile, type) return state_result(True, 'Created new zone', domain, result)
Ensures a record is present. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param type: Zone type (master / slave), defaults to master :type type: ``str`` :param profile: The profile key :type profile: ``str``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_dns.py#L74-L95
[ "def state_result(result, message, name, changes=None):\n if changes is None:\n changes = {}\n return {'result': result,\n 'comment': message,\n 'name': name,\n 'changes': changes}\n" ]
# -*- coding: utf-8 -*- ''' Manage DNS records and zones using libcloud :codeauthor: Anthony Shaw <anthonyshaw@apache.org> .. versionadded:: 2016.11.0 Create and delete DNS records or zones through Libcloud. Libcloud's DNS system supports over 20 DNS providers including Amazon, Google, GoDaddy, Softlayer This module uses ``libcloud``, which can be installed via package, or pip. :configuration: This module uses a configuration profile for one or multiple DNS providers .. code-block:: yaml libcloud_dns: profile1: driver: godaddy key: 2orgk34kgk34g profile2: driver: route53 key: blah secret: blah Example: .. code-block:: yaml my-zone: libcloud_dns.zone_present: - name: mywebsite.com - profile: profile1 my-website: libcloud_dns.record_present: - name: www - zone: mywebsite.com - type: A - data: 12.34.32.3 - profile: profile1 - require: - libcloud_dns: my-zone :depends: apache-libcloud ''' # Import Python Libs from __future__ import absolute_import # Import salt libs import salt.utils.compat def __virtual__(): return True def __init__(opts): salt.utils.compat.pack_dunder(__name__) def state_result(result, message, name, changes=None): if changes is None: changes = {} return {'result': result, 'comment': message, 'name': name, 'changes': changes} def zone_absent(domain, profile): ''' Ensures a record is absent. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) matching_zone = [z for z in zones if z['domain'] == domain] if not matching_zone: return state_result(True, 'Zone already absent', domain) else: result = __salt__['libcloud_dns.delete_zone'](matching_zone[0]['id'], profile) return state_result(result, 'Deleted zone', domain) def record_present(name, zone, type, data, profile): ''' Ensures a record is present. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) try: matching_zone = [z for z in zones if z['domain'] == zone][0] except IndexError: return state_result(False, 'Could not locate zone', name) records = __salt__['libcloud_dns.list_records'](matching_zone['id'], profile) matching_records = [record for record in records if record['name'] == name and record['type'] == type and record['data'] == data] if not matching_records: result = __salt__['libcloud_dns.create_record']( name, matching_zone['id'], type, data, profile) return state_result(True, 'Created new record', name, result) else: return state_result(True, 'Record already exists', name) def record_absent(name, zone, type, data, profile): ''' Ensures a record is absent. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) try: matching_zone = [z for z in zones if z['domain'] == zone][0] except IndexError: return state_result(False, 'Zone could not be found', name) records = __salt__['libcloud_dns.list_records'](matching_zone['id'], profile) matching_records = [record for record in records if record['name'] == name and record['type'] == type and record['data'] == data] if matching_records: result = [] for record in matching_records: result.append(__salt__['libcloud_dns.delete_record']( matching_zone['id'], record['id'], profile)) return state_result(all(result), 'Removed {0} records'.format(len(result)), name) else: return state_result(True, 'Records already absent', name)
saltstack/salt
salt/states/libcloud_dns.py
zone_absent
python
def zone_absent(domain, profile): ''' Ensures a record is absent. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) matching_zone = [z for z in zones if z['domain'] == domain] if not matching_zone: return state_result(True, 'Zone already absent', domain) else: result = __salt__['libcloud_dns.delete_zone'](matching_zone[0]['id'], profile) return state_result(result, 'Deleted zone', domain)
Ensures a record is absent. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param profile: The profile key :type profile: ``str``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_dns.py#L98-L114
[ "def state_result(result, message, name, changes=None):\n if changes is None:\n changes = {}\n return {'result': result,\n 'comment': message,\n 'name': name,\n 'changes': changes}\n" ]
# -*- coding: utf-8 -*- ''' Manage DNS records and zones using libcloud :codeauthor: Anthony Shaw <anthonyshaw@apache.org> .. versionadded:: 2016.11.0 Create and delete DNS records or zones through Libcloud. Libcloud's DNS system supports over 20 DNS providers including Amazon, Google, GoDaddy, Softlayer This module uses ``libcloud``, which can be installed via package, or pip. :configuration: This module uses a configuration profile for one or multiple DNS providers .. code-block:: yaml libcloud_dns: profile1: driver: godaddy key: 2orgk34kgk34g profile2: driver: route53 key: blah secret: blah Example: .. code-block:: yaml my-zone: libcloud_dns.zone_present: - name: mywebsite.com - profile: profile1 my-website: libcloud_dns.record_present: - name: www - zone: mywebsite.com - type: A - data: 12.34.32.3 - profile: profile1 - require: - libcloud_dns: my-zone :depends: apache-libcloud ''' # Import Python Libs from __future__ import absolute_import # Import salt libs import salt.utils.compat def __virtual__(): return True def __init__(opts): salt.utils.compat.pack_dunder(__name__) def state_result(result, message, name, changes=None): if changes is None: changes = {} return {'result': result, 'comment': message, 'name': name, 'changes': changes} def zone_present(domain, type, profile): ''' Ensures a record is present. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param type: Zone type (master / slave), defaults to master :type type: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) if not type: type = 'master' matching_zone = [z for z in zones if z['domain'] == domain] if matching_zone: return state_result(True, 'Zone already exists', domain) else: result = __salt__['libcloud_dns.create_zone'](domain, profile, type) return state_result(True, 'Created new zone', domain, result) def record_present(name, zone, type, data, profile): ''' Ensures a record is present. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) try: matching_zone = [z for z in zones if z['domain'] == zone][0] except IndexError: return state_result(False, 'Could not locate zone', name) records = __salt__['libcloud_dns.list_records'](matching_zone['id'], profile) matching_records = [record for record in records if record['name'] == name and record['type'] == type and record['data'] == data] if not matching_records: result = __salt__['libcloud_dns.create_record']( name, matching_zone['id'], type, data, profile) return state_result(True, 'Created new record', name, result) else: return state_result(True, 'Record already exists', name) def record_absent(name, zone, type, data, profile): ''' Ensures a record is absent. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) try: matching_zone = [z for z in zones if z['domain'] == zone][0] except IndexError: return state_result(False, 'Zone could not be found', name) records = __salt__['libcloud_dns.list_records'](matching_zone['id'], profile) matching_records = [record for record in records if record['name'] == name and record['type'] == type and record['data'] == data] if matching_records: result = [] for record in matching_records: result.append(__salt__['libcloud_dns.delete_record']( matching_zone['id'], record['id'], profile)) return state_result(all(result), 'Removed {0} records'.format(len(result)), name) else: return state_result(True, 'Records already absent', name)
saltstack/salt
salt/states/libcloud_dns.py
record_present
python
def record_present(name, zone, type, data, profile): ''' Ensures a record is present. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) try: matching_zone = [z for z in zones if z['domain'] == zone][0] except IndexError: return state_result(False, 'Could not locate zone', name) records = __salt__['libcloud_dns.list_records'](matching_zone['id'], profile) matching_records = [record for record in records if record['name'] == name and record['type'] == type and record['data'] == data] if not matching_records: result = __salt__['libcloud_dns.create_record']( name, matching_zone['id'], type, data, profile) return state_result(True, 'Created new record', name, result) else: return state_result(True, 'Record already exists', name)
Ensures a record is present. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_dns.py#L117-L155
[ "def state_result(result, message, name, changes=None):\n if changes is None:\n changes = {}\n return {'result': result,\n 'comment': message,\n 'name': name,\n 'changes': changes}\n" ]
# -*- coding: utf-8 -*- ''' Manage DNS records and zones using libcloud :codeauthor: Anthony Shaw <anthonyshaw@apache.org> .. versionadded:: 2016.11.0 Create and delete DNS records or zones through Libcloud. Libcloud's DNS system supports over 20 DNS providers including Amazon, Google, GoDaddy, Softlayer This module uses ``libcloud``, which can be installed via package, or pip. :configuration: This module uses a configuration profile for one or multiple DNS providers .. code-block:: yaml libcloud_dns: profile1: driver: godaddy key: 2orgk34kgk34g profile2: driver: route53 key: blah secret: blah Example: .. code-block:: yaml my-zone: libcloud_dns.zone_present: - name: mywebsite.com - profile: profile1 my-website: libcloud_dns.record_present: - name: www - zone: mywebsite.com - type: A - data: 12.34.32.3 - profile: profile1 - require: - libcloud_dns: my-zone :depends: apache-libcloud ''' # Import Python Libs from __future__ import absolute_import # Import salt libs import salt.utils.compat def __virtual__(): return True def __init__(opts): salt.utils.compat.pack_dunder(__name__) def state_result(result, message, name, changes=None): if changes is None: changes = {} return {'result': result, 'comment': message, 'name': name, 'changes': changes} def zone_present(domain, type, profile): ''' Ensures a record is present. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param type: Zone type (master / slave), defaults to master :type type: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) if not type: type = 'master' matching_zone = [z for z in zones if z['domain'] == domain] if matching_zone: return state_result(True, 'Zone already exists', domain) else: result = __salt__['libcloud_dns.create_zone'](domain, profile, type) return state_result(True, 'Created new zone', domain, result) def zone_absent(domain, profile): ''' Ensures a record is absent. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) matching_zone = [z for z in zones if z['domain'] == domain] if not matching_zone: return state_result(True, 'Zone already absent', domain) else: result = __salt__['libcloud_dns.delete_zone'](matching_zone[0]['id'], profile) return state_result(result, 'Deleted zone', domain) def record_absent(name, zone, type, data, profile): ''' Ensures a record is absent. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) try: matching_zone = [z for z in zones if z['domain'] == zone][0] except IndexError: return state_result(False, 'Zone could not be found', name) records = __salt__['libcloud_dns.list_records'](matching_zone['id'], profile) matching_records = [record for record in records if record['name'] == name and record['type'] == type and record['data'] == data] if matching_records: result = [] for record in matching_records: result.append(__salt__['libcloud_dns.delete_record']( matching_zone['id'], record['id'], profile)) return state_result(all(result), 'Removed {0} records'.format(len(result)), name) else: return state_result(True, 'Records already absent', name)
saltstack/salt
salt/states/libcloud_dns.py
record_absent
python
def record_absent(name, zone, type, data, profile): ''' Ensures a record is absent. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) try: matching_zone = [z for z in zones if z['domain'] == zone][0] except IndexError: return state_result(False, 'Zone could not be found', name) records = __salt__['libcloud_dns.list_records'](matching_zone['id'], profile) matching_records = [record for record in records if record['name'] == name and record['type'] == type and record['data'] == data] if matching_records: result = [] for record in matching_records: result.append(__salt__['libcloud_dns.delete_record']( matching_zone['id'], record['id'], profile)) return state_result(all(result), 'Removed {0} records'.format(len(result)), name) else: return state_result(True, 'Records already absent', name)
Ensures a record is absent. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_dns.py#L158-L199
[ "def state_result(result, message, name, changes=None):\n if changes is None:\n changes = {}\n return {'result': result,\n 'comment': message,\n 'name': name,\n 'changes': changes}\n" ]
# -*- coding: utf-8 -*- ''' Manage DNS records and zones using libcloud :codeauthor: Anthony Shaw <anthonyshaw@apache.org> .. versionadded:: 2016.11.0 Create and delete DNS records or zones through Libcloud. Libcloud's DNS system supports over 20 DNS providers including Amazon, Google, GoDaddy, Softlayer This module uses ``libcloud``, which can be installed via package, or pip. :configuration: This module uses a configuration profile for one or multiple DNS providers .. code-block:: yaml libcloud_dns: profile1: driver: godaddy key: 2orgk34kgk34g profile2: driver: route53 key: blah secret: blah Example: .. code-block:: yaml my-zone: libcloud_dns.zone_present: - name: mywebsite.com - profile: profile1 my-website: libcloud_dns.record_present: - name: www - zone: mywebsite.com - type: A - data: 12.34.32.3 - profile: profile1 - require: - libcloud_dns: my-zone :depends: apache-libcloud ''' # Import Python Libs from __future__ import absolute_import # Import salt libs import salt.utils.compat def __virtual__(): return True def __init__(opts): salt.utils.compat.pack_dunder(__name__) def state_result(result, message, name, changes=None): if changes is None: changes = {} return {'result': result, 'comment': message, 'name': name, 'changes': changes} def zone_present(domain, type, profile): ''' Ensures a record is present. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param type: Zone type (master / slave), defaults to master :type type: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) if not type: type = 'master' matching_zone = [z for z in zones if z['domain'] == domain] if matching_zone: return state_result(True, 'Zone already exists', domain) else: result = __salt__['libcloud_dns.create_zone'](domain, profile, type) return state_result(True, 'Created new zone', domain, result) def zone_absent(domain, profile): ''' Ensures a record is absent. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) matching_zone = [z for z in zones if z['domain'] == domain] if not matching_zone: return state_result(True, 'Zone already absent', domain) else: result = __salt__['libcloud_dns.delete_zone'](matching_zone[0]['id'], profile) return state_result(result, 'Deleted zone', domain) def record_present(name, zone, type, data, profile): ''' Ensures a record is present. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) try: matching_zone = [z for z in zones if z['domain'] == zone][0] except IndexError: return state_result(False, 'Could not locate zone', name) records = __salt__['libcloud_dns.list_records'](matching_zone['id'], profile) matching_records = [record for record in records if record['name'] == name and record['type'] == type and record['data'] == data] if not matching_records: result = __salt__['libcloud_dns.create_record']( name, matching_zone['id'], type, data, profile) return state_result(True, 'Created new record', name, result) else: return state_result(True, 'Record already exists', name)
saltstack/salt
salt/modules/mod_random.py
hash
python
def hash(value, algorithm='sha512'): ''' .. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: bash salt '*' random.hash 'I am a string' md5 ''' if six.PY3 and isinstance(value, six.string_types): # Under Python 3 we must work with bytes value = value.encode(__salt_system_encoding__) if hasattr(hashlib, ALGORITHMS_ATTR_NAME) and algorithm in getattr(hashlib, ALGORITHMS_ATTR_NAME): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() elif hasattr(hashlib, algorithm): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() else: raise SaltInvocationError('You must specify a valid algorithm.') return out
.. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: bash salt '*' random.hash 'I am a string' md5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mod_random.py#L46-L80
null
# -*- coding: utf-8 -*- ''' Provides access to randomness generators. ========================================= .. versionadded:: 2014.7.0 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import base64 import hashlib import random # Import salt libs import salt.utils.pycrypto from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six if six.PY2: ALGORITHMS_ATTR_NAME = 'algorithms' else: ALGORITHMS_ATTR_NAME = 'algorithms_guaranteed' # Define the module's virtual name __virtualname__ = 'random' def __virtual__(algorithm='sha512'): ''' Sanity check for compatibility with Python 2.6 / 2.7 ''' # The hashlib function on Python <= 2.6 does not provide the attribute 'algorithms' # This attribute was introduced on Python >= 2.7 if six.PY2: if not hasattr(hashlib, 'algorithms') and not hasattr(hashlib, algorithm): return (False, 'The random execution module cannot be loaded: only available in Python >= 2.7.') # Under python >= 3.2, the attribute name changed to 'algorithms_guaranteed' # Since we support python 3.4+, we're good return __virtualname__ def str_encode(value, encoder='base64'): ''' .. versionadded:: 2014.7.0 value The value to be encoded. encoder : base64 The encoder to use on the subsequent string. CLI Example: .. code-block:: bash salt '*' random.str_encode 'I am a new string' base64 ''' if six.PY2: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') else: if isinstance(value, six.string_types): value = value.encode(__salt_system_encoding__) if encoder == 'base64': try: out = base64.b64encode(value) out = out.decode(__salt_system_encoding__) except TypeError: raise SaltInvocationError('Value must be an encode-able string') else: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') return out def get_str(length=20): ''' .. versionadded:: 2014.7.0 Returns a random string of the specified length. length : 20 Any valid number of bytes. CLI Example: .. code-block:: bash salt '*' random.get_str 128 ''' return salt.utils.pycrypto.secure_password(length) def shadow_hash(crypt_salt=None, password=None, algorithm='sha512'): ''' Generates a salted hash suitable for /etc/shadow. crypt_salt : None Salt to be used in the generation of the hash. If one is not provided, a random salt will be generated. password : None Value to be salted and hashed. If one is not provided, a random password will be generated. algorithm : sha512 Hash algorithm to use. CLI Example: .. code-block:: bash salt '*' random.shadow_hash 'My5alT' 'MyP@asswd' md5 ''' return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) def rand_int(start=1, end=10, seed=None): ''' Returns a random integer number between the start and end number. .. versionadded: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. versionchanged:: 2019.2.0 Added seed argument. Will return the same result when run with the same seed. CLI Example: .. code-block:: bash salt '*' random.rand_int 1 10 ''' if seed is not None: random.seed(seed) return random.randint(start, end) def seed(range=10, hash=None): ''' Returns a random number within a range. Optional hash argument can be any hashable object. If hash is omitted or None, the id of the minion is used. .. versionadded: 2015.8.0 hash: None Any hashable object. range: 10 Any valid integer number CLI Example: .. code-block:: bash salt '*' random.seed 10 hash=None ''' if hash is None: hash = __grains__['id'] random.seed(hash) return random.randrange(range)
saltstack/salt
salt/modules/mod_random.py
str_encode
python
def str_encode(value, encoder='base64'): ''' .. versionadded:: 2014.7.0 value The value to be encoded. encoder : base64 The encoder to use on the subsequent string. CLI Example: .. code-block:: bash salt '*' random.str_encode 'I am a new string' base64 ''' if six.PY2: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') else: if isinstance(value, six.string_types): value = value.encode(__salt_system_encoding__) if encoder == 'base64': try: out = base64.b64encode(value) out = out.decode(__salt_system_encoding__) except TypeError: raise SaltInvocationError('Value must be an encode-able string') else: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') return out
.. versionadded:: 2014.7.0 value The value to be encoded. encoder : base64 The encoder to use on the subsequent string. CLI Example: .. code-block:: bash salt '*' random.str_encode 'I am a new string' base64
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mod_random.py#L83-L122
null
# -*- coding: utf-8 -*- ''' Provides access to randomness generators. ========================================= .. versionadded:: 2014.7.0 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import base64 import hashlib import random # Import salt libs import salt.utils.pycrypto from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six if six.PY2: ALGORITHMS_ATTR_NAME = 'algorithms' else: ALGORITHMS_ATTR_NAME = 'algorithms_guaranteed' # Define the module's virtual name __virtualname__ = 'random' def __virtual__(algorithm='sha512'): ''' Sanity check for compatibility with Python 2.6 / 2.7 ''' # The hashlib function on Python <= 2.6 does not provide the attribute 'algorithms' # This attribute was introduced on Python >= 2.7 if six.PY2: if not hasattr(hashlib, 'algorithms') and not hasattr(hashlib, algorithm): return (False, 'The random execution module cannot be loaded: only available in Python >= 2.7.') # Under python >= 3.2, the attribute name changed to 'algorithms_guaranteed' # Since we support python 3.4+, we're good return __virtualname__ def hash(value, algorithm='sha512'): ''' .. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: bash salt '*' random.hash 'I am a string' md5 ''' if six.PY3 and isinstance(value, six.string_types): # Under Python 3 we must work with bytes value = value.encode(__salt_system_encoding__) if hasattr(hashlib, ALGORITHMS_ATTR_NAME) and algorithm in getattr(hashlib, ALGORITHMS_ATTR_NAME): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() elif hasattr(hashlib, algorithm): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() else: raise SaltInvocationError('You must specify a valid algorithm.') return out def get_str(length=20): ''' .. versionadded:: 2014.7.0 Returns a random string of the specified length. length : 20 Any valid number of bytes. CLI Example: .. code-block:: bash salt '*' random.get_str 128 ''' return salt.utils.pycrypto.secure_password(length) def shadow_hash(crypt_salt=None, password=None, algorithm='sha512'): ''' Generates a salted hash suitable for /etc/shadow. crypt_salt : None Salt to be used in the generation of the hash. If one is not provided, a random salt will be generated. password : None Value to be salted and hashed. If one is not provided, a random password will be generated. algorithm : sha512 Hash algorithm to use. CLI Example: .. code-block:: bash salt '*' random.shadow_hash 'My5alT' 'MyP@asswd' md5 ''' return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) def rand_int(start=1, end=10, seed=None): ''' Returns a random integer number between the start and end number. .. versionadded: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. versionchanged:: 2019.2.0 Added seed argument. Will return the same result when run with the same seed. CLI Example: .. code-block:: bash salt '*' random.rand_int 1 10 ''' if seed is not None: random.seed(seed) return random.randint(start, end) def seed(range=10, hash=None): ''' Returns a random number within a range. Optional hash argument can be any hashable object. If hash is omitted or None, the id of the minion is used. .. versionadded: 2015.8.0 hash: None Any hashable object. range: 10 Any valid integer number CLI Example: .. code-block:: bash salt '*' random.seed 10 hash=None ''' if hash is None: hash = __grains__['id'] random.seed(hash) return random.randrange(range)
saltstack/salt
salt/modules/mod_random.py
shadow_hash
python
def shadow_hash(crypt_salt=None, password=None, algorithm='sha512'): ''' Generates a salted hash suitable for /etc/shadow. crypt_salt : None Salt to be used in the generation of the hash. If one is not provided, a random salt will be generated. password : None Value to be salted and hashed. If one is not provided, a random password will be generated. algorithm : sha512 Hash algorithm to use. CLI Example: .. code-block:: bash salt '*' random.shadow_hash 'My5alT' 'MyP@asswd' md5 ''' return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm)
Generates a salted hash suitable for /etc/shadow. crypt_salt : None Salt to be used in the generation of the hash. If one is not provided, a random salt will be generated. password : None Value to be salted and hashed. If one is not provided, a random password will be generated. algorithm : sha512 Hash algorithm to use. CLI Example: .. code-block:: bash salt '*' random.shadow_hash 'My5alT' 'MyP@asswd' md5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mod_random.py#L143-L164
[ "def gen_hash(crypt_salt=None, password=None, algorithm='sha512'):\n '''\n Generate /etc/shadow hash\n '''\n if not HAS_CRYPT:\n raise SaltInvocationError('No crypt module for windows')\n\n hash_algorithms = dict(\n md5='$1$', blowfish='$2a$', sha256='$5$', sha512='$6$'\n )\n if algorithm not in hash_algorithms:\n raise SaltInvocationError(\n 'Algorithm \\'{0}\\' is not supported'.format(algorithm)\n )\n\n if password is None:\n password = secure_password()\n\n if crypt_salt is None:\n crypt_salt = secure_password(8)\n\n crypt_salt = hash_algorithms[algorithm] + crypt_salt\n\n return crypt.crypt(password, crypt_salt)\n" ]
# -*- coding: utf-8 -*- ''' Provides access to randomness generators. ========================================= .. versionadded:: 2014.7.0 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import base64 import hashlib import random # Import salt libs import salt.utils.pycrypto from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six if six.PY2: ALGORITHMS_ATTR_NAME = 'algorithms' else: ALGORITHMS_ATTR_NAME = 'algorithms_guaranteed' # Define the module's virtual name __virtualname__ = 'random' def __virtual__(algorithm='sha512'): ''' Sanity check for compatibility with Python 2.6 / 2.7 ''' # The hashlib function on Python <= 2.6 does not provide the attribute 'algorithms' # This attribute was introduced on Python >= 2.7 if six.PY2: if not hasattr(hashlib, 'algorithms') and not hasattr(hashlib, algorithm): return (False, 'The random execution module cannot be loaded: only available in Python >= 2.7.') # Under python >= 3.2, the attribute name changed to 'algorithms_guaranteed' # Since we support python 3.4+, we're good return __virtualname__ def hash(value, algorithm='sha512'): ''' .. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: bash salt '*' random.hash 'I am a string' md5 ''' if six.PY3 and isinstance(value, six.string_types): # Under Python 3 we must work with bytes value = value.encode(__salt_system_encoding__) if hasattr(hashlib, ALGORITHMS_ATTR_NAME) and algorithm in getattr(hashlib, ALGORITHMS_ATTR_NAME): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() elif hasattr(hashlib, algorithm): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() else: raise SaltInvocationError('You must specify a valid algorithm.') return out def str_encode(value, encoder='base64'): ''' .. versionadded:: 2014.7.0 value The value to be encoded. encoder : base64 The encoder to use on the subsequent string. CLI Example: .. code-block:: bash salt '*' random.str_encode 'I am a new string' base64 ''' if six.PY2: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') else: if isinstance(value, six.string_types): value = value.encode(__salt_system_encoding__) if encoder == 'base64': try: out = base64.b64encode(value) out = out.decode(__salt_system_encoding__) except TypeError: raise SaltInvocationError('Value must be an encode-able string') else: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') return out def get_str(length=20): ''' .. versionadded:: 2014.7.0 Returns a random string of the specified length. length : 20 Any valid number of bytes. CLI Example: .. code-block:: bash salt '*' random.get_str 128 ''' return salt.utils.pycrypto.secure_password(length) def rand_int(start=1, end=10, seed=None): ''' Returns a random integer number between the start and end number. .. versionadded: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. versionchanged:: 2019.2.0 Added seed argument. Will return the same result when run with the same seed. CLI Example: .. code-block:: bash salt '*' random.rand_int 1 10 ''' if seed is not None: random.seed(seed) return random.randint(start, end) def seed(range=10, hash=None): ''' Returns a random number within a range. Optional hash argument can be any hashable object. If hash is omitted or None, the id of the minion is used. .. versionadded: 2015.8.0 hash: None Any hashable object. range: 10 Any valid integer number CLI Example: .. code-block:: bash salt '*' random.seed 10 hash=None ''' if hash is None: hash = __grains__['id'] random.seed(hash) return random.randrange(range)
saltstack/salt
salt/modules/mod_random.py
rand_int
python
def rand_int(start=1, end=10, seed=None): ''' Returns a random integer number between the start and end number. .. versionadded: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. versionchanged:: 2019.2.0 Added seed argument. Will return the same result when run with the same seed. CLI Example: .. code-block:: bash salt '*' random.rand_int 1 10 ''' if seed is not None: random.seed(seed) return random.randint(start, end)
Returns a random integer number between the start and end number. .. versionadded: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. versionchanged:: 2019.2.0 Added seed argument. Will return the same result when run with the same seed. CLI Example: .. code-block:: bash salt '*' random.rand_int 1 10
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mod_random.py#L167-L194
null
# -*- coding: utf-8 -*- ''' Provides access to randomness generators. ========================================= .. versionadded:: 2014.7.0 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import base64 import hashlib import random # Import salt libs import salt.utils.pycrypto from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six if six.PY2: ALGORITHMS_ATTR_NAME = 'algorithms' else: ALGORITHMS_ATTR_NAME = 'algorithms_guaranteed' # Define the module's virtual name __virtualname__ = 'random' def __virtual__(algorithm='sha512'): ''' Sanity check for compatibility with Python 2.6 / 2.7 ''' # The hashlib function on Python <= 2.6 does not provide the attribute 'algorithms' # This attribute was introduced on Python >= 2.7 if six.PY2: if not hasattr(hashlib, 'algorithms') and not hasattr(hashlib, algorithm): return (False, 'The random execution module cannot be loaded: only available in Python >= 2.7.') # Under python >= 3.2, the attribute name changed to 'algorithms_guaranteed' # Since we support python 3.4+, we're good return __virtualname__ def hash(value, algorithm='sha512'): ''' .. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: bash salt '*' random.hash 'I am a string' md5 ''' if six.PY3 and isinstance(value, six.string_types): # Under Python 3 we must work with bytes value = value.encode(__salt_system_encoding__) if hasattr(hashlib, ALGORITHMS_ATTR_NAME) and algorithm in getattr(hashlib, ALGORITHMS_ATTR_NAME): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() elif hasattr(hashlib, algorithm): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() else: raise SaltInvocationError('You must specify a valid algorithm.') return out def str_encode(value, encoder='base64'): ''' .. versionadded:: 2014.7.0 value The value to be encoded. encoder : base64 The encoder to use on the subsequent string. CLI Example: .. code-block:: bash salt '*' random.str_encode 'I am a new string' base64 ''' if six.PY2: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') else: if isinstance(value, six.string_types): value = value.encode(__salt_system_encoding__) if encoder == 'base64': try: out = base64.b64encode(value) out = out.decode(__salt_system_encoding__) except TypeError: raise SaltInvocationError('Value must be an encode-able string') else: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') return out def get_str(length=20): ''' .. versionadded:: 2014.7.0 Returns a random string of the specified length. length : 20 Any valid number of bytes. CLI Example: .. code-block:: bash salt '*' random.get_str 128 ''' return salt.utils.pycrypto.secure_password(length) def shadow_hash(crypt_salt=None, password=None, algorithm='sha512'): ''' Generates a salted hash suitable for /etc/shadow. crypt_salt : None Salt to be used in the generation of the hash. If one is not provided, a random salt will be generated. password : None Value to be salted and hashed. If one is not provided, a random password will be generated. algorithm : sha512 Hash algorithm to use. CLI Example: .. code-block:: bash salt '*' random.shadow_hash 'My5alT' 'MyP@asswd' md5 ''' return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) def seed(range=10, hash=None): ''' Returns a random number within a range. Optional hash argument can be any hashable object. If hash is omitted or None, the id of the minion is used. .. versionadded: 2015.8.0 hash: None Any hashable object. range: 10 Any valid integer number CLI Example: .. code-block:: bash salt '*' random.seed 10 hash=None ''' if hash is None: hash = __grains__['id'] random.seed(hash) return random.randrange(range)
saltstack/salt
salt/modules/mod_random.py
seed
python
def seed(range=10, hash=None): ''' Returns a random number within a range. Optional hash argument can be any hashable object. If hash is omitted or None, the id of the minion is used. .. versionadded: 2015.8.0 hash: None Any hashable object. range: 10 Any valid integer number CLI Example: .. code-block:: bash salt '*' random.seed 10 hash=None ''' if hash is None: hash = __grains__['id'] random.seed(hash) return random.randrange(range)
Returns a random number within a range. Optional hash argument can be any hashable object. If hash is omitted or None, the id of the minion is used. .. versionadded: 2015.8.0 hash: None Any hashable object. range: 10 Any valid integer number CLI Example: .. code-block:: bash salt '*' random.seed 10 hash=None
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mod_random.py#L197-L220
null
# -*- coding: utf-8 -*- ''' Provides access to randomness generators. ========================================= .. versionadded:: 2014.7.0 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import base64 import hashlib import random # Import salt libs import salt.utils.pycrypto from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six if six.PY2: ALGORITHMS_ATTR_NAME = 'algorithms' else: ALGORITHMS_ATTR_NAME = 'algorithms_guaranteed' # Define the module's virtual name __virtualname__ = 'random' def __virtual__(algorithm='sha512'): ''' Sanity check for compatibility with Python 2.6 / 2.7 ''' # The hashlib function on Python <= 2.6 does not provide the attribute 'algorithms' # This attribute was introduced on Python >= 2.7 if six.PY2: if not hasattr(hashlib, 'algorithms') and not hasattr(hashlib, algorithm): return (False, 'The random execution module cannot be loaded: only available in Python >= 2.7.') # Under python >= 3.2, the attribute name changed to 'algorithms_guaranteed' # Since we support python 3.4+, we're good return __virtualname__ def hash(value, algorithm='sha512'): ''' .. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: bash salt '*' random.hash 'I am a string' md5 ''' if six.PY3 and isinstance(value, six.string_types): # Under Python 3 we must work with bytes value = value.encode(__salt_system_encoding__) if hasattr(hashlib, ALGORITHMS_ATTR_NAME) and algorithm in getattr(hashlib, ALGORITHMS_ATTR_NAME): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() elif hasattr(hashlib, algorithm): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() else: raise SaltInvocationError('You must specify a valid algorithm.') return out def str_encode(value, encoder='base64'): ''' .. versionadded:: 2014.7.0 value The value to be encoded. encoder : base64 The encoder to use on the subsequent string. CLI Example: .. code-block:: bash salt '*' random.str_encode 'I am a new string' base64 ''' if six.PY2: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') else: if isinstance(value, six.string_types): value = value.encode(__salt_system_encoding__) if encoder == 'base64': try: out = base64.b64encode(value) out = out.decode(__salt_system_encoding__) except TypeError: raise SaltInvocationError('Value must be an encode-able string') else: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') return out def get_str(length=20): ''' .. versionadded:: 2014.7.0 Returns a random string of the specified length. length : 20 Any valid number of bytes. CLI Example: .. code-block:: bash salt '*' random.get_str 128 ''' return salt.utils.pycrypto.secure_password(length) def shadow_hash(crypt_salt=None, password=None, algorithm='sha512'): ''' Generates a salted hash suitable for /etc/shadow. crypt_salt : None Salt to be used in the generation of the hash. If one is not provided, a random salt will be generated. password : None Value to be salted and hashed. If one is not provided, a random password will be generated. algorithm : sha512 Hash algorithm to use. CLI Example: .. code-block:: bash salt '*' random.shadow_hash 'My5alT' 'MyP@asswd' md5 ''' return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) def rand_int(start=1, end=10, seed=None): ''' Returns a random integer number between the start and end number. .. versionadded: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. versionchanged:: 2019.2.0 Added seed argument. Will return the same result when run with the same seed. CLI Example: .. code-block:: bash salt '*' random.rand_int 1 10 ''' if seed is not None: random.seed(seed) return random.randint(start, end)
saltstack/salt
salt/auth/mysql.py
__get_connection_info
python
def __get_connection_info(): ''' Grab MySQL Connection Details ''' conn_info = {} try: conn_info['hostname'] = __opts__['mysql_auth']['hostname'] conn_info['username'] = __opts__['mysql_auth']['username'] conn_info['password'] = __opts__['mysql_auth']['password'] conn_info['database'] = __opts__['mysql_auth']['database'] conn_info['auth_sql'] = __opts__['mysql_auth']['auth_sql'] except KeyError as e: log.error('%s does not exist', e) return None return conn_info
Grab MySQL Connection Details
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/mysql.py#L83-L100
null
# -*- coding: utf-8 -*- ''' Provide authentication using MySQL. When using MySQL as an authentication backend, you will need to create or use an existing table that has a username and a password column. To get started, create a simple table that holds just a username and a password. The password field will hold a SHA256 checksum. .. code-block:: sql CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(25) DEFAULT NULL, `password` varchar(70) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; To create a user within MySQL, execute the following statement. .. code-block:: sql INSERT INTO users VALUES (NULL, 'diana', SHA2('secret', 256)) .. code-block:: yaml mysql_auth: hostname: localhost database: SaltStack username: root password: letmein auth_sql: 'SELECT username FROM users WHERE username = "{0}" AND password = SHA2("{1}", 256)' The `auth_sql` contains the SQL that will validate a user to ensure they are correctly authenticated. This is where you can specify other SQL queries to authenticate users. Enable MySQL authentication. .. code-block:: yaml external_auth: mysql: damian: - test.* :depends: - MySQL-python Python module ''' from __future__ import absolute_import, print_function, unicode_literals import logging log = logging.getLogger(__name__) try: # Trying to import MySQLdb import MySQLdb import MySQLdb.cursors import MySQLdb.converters from MySQLdb.connections import OperationalError except ImportError: try: # MySQLdb import failed, try to import PyMySQL import pymysql pymysql.install_as_MySQLdb() import MySQLdb import MySQLdb.cursors import MySQLdb.converters from MySQLdb.err import OperationalError except ImportError: MySQLdb = None def __virtual__(): ''' Confirm that a python mysql client is installed. ''' return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else '' def auth(username, password): ''' Authenticate using a MySQL user table ''' _info = __get_connection_info() if _info is None: return False try: conn = MySQLdb.connect(_info['hostname'], _info['username'], _info['password'], _info['database']) except OperationalError as e: log.error(e) return False cur = conn.cursor() cur.execute(_info['auth_sql'].format(username, password)) if cur.rowcount == 1: return True return False
saltstack/salt
salt/auth/mysql.py
auth
python
def auth(username, password): ''' Authenticate using a MySQL user table ''' _info = __get_connection_info() if _info is None: return False try: conn = MySQLdb.connect(_info['hostname'], _info['username'], _info['password'], _info['database']) except OperationalError as e: log.error(e) return False cur = conn.cursor() cur.execute(_info['auth_sql'].format(username, password)) if cur.rowcount == 1: return True return False
Authenticate using a MySQL user table
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/mysql.py#L103-L127
[ "def __get_connection_info():\n '''\n Grab MySQL Connection Details\n '''\n conn_info = {}\n\n try:\n conn_info['hostname'] = __opts__['mysql_auth']['hostname']\n conn_info['username'] = __opts__['mysql_auth']['username']\n conn_info['password'] = __opts__['mysql_auth']['password']\n conn_info['database'] = __opts__['mysql_auth']['database']\n\n conn_info['auth_sql'] = __opts__['mysql_auth']['auth_sql']\n except KeyError as e:\n log.error('%s does not exist', e)\n return None\n\n return conn_info\n" ]
# -*- coding: utf-8 -*- ''' Provide authentication using MySQL. When using MySQL as an authentication backend, you will need to create or use an existing table that has a username and a password column. To get started, create a simple table that holds just a username and a password. The password field will hold a SHA256 checksum. .. code-block:: sql CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(25) DEFAULT NULL, `password` varchar(70) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; To create a user within MySQL, execute the following statement. .. code-block:: sql INSERT INTO users VALUES (NULL, 'diana', SHA2('secret', 256)) .. code-block:: yaml mysql_auth: hostname: localhost database: SaltStack username: root password: letmein auth_sql: 'SELECT username FROM users WHERE username = "{0}" AND password = SHA2("{1}", 256)' The `auth_sql` contains the SQL that will validate a user to ensure they are correctly authenticated. This is where you can specify other SQL queries to authenticate users. Enable MySQL authentication. .. code-block:: yaml external_auth: mysql: damian: - test.* :depends: - MySQL-python Python module ''' from __future__ import absolute_import, print_function, unicode_literals import logging log = logging.getLogger(__name__) try: # Trying to import MySQLdb import MySQLdb import MySQLdb.cursors import MySQLdb.converters from MySQLdb.connections import OperationalError except ImportError: try: # MySQLdb import failed, try to import PyMySQL import pymysql pymysql.install_as_MySQLdb() import MySQLdb import MySQLdb.cursors import MySQLdb.converters from MySQLdb.err import OperationalError except ImportError: MySQLdb = None def __virtual__(): ''' Confirm that a python mysql client is installed. ''' return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else '' def __get_connection_info(): ''' Grab MySQL Connection Details ''' conn_info = {} try: conn_info['hostname'] = __opts__['mysql_auth']['hostname'] conn_info['username'] = __opts__['mysql_auth']['username'] conn_info['password'] = __opts__['mysql_auth']['password'] conn_info['database'] = __opts__['mysql_auth']['database'] conn_info['auth_sql'] = __opts__['mysql_auth']['auth_sql'] except KeyError as e: log.error('%s does not exist', e) return None return conn_info
saltstack/salt
salt/modules/uptime.py
create
python
def create(name, **params): '''Create a check on a given URL. Additional parameters can be used and are passed to API (for example interval, maxTime, etc). See the documentation https://github.com/fzaninotto/uptime for a full list of the parameters. CLI Example: .. code-block:: bash salt '*' uptime.create http://example.org ''' if check_exists(name): msg = 'Trying to create check that already exists : {0}'.format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug('[uptime] trying PUT request') params.update(url=name) req = requests.put('{0}/api/checks'.format(application_url), data=params) if not req.ok: raise CommandExecutionError( 'request to uptime failed : {0}'.format(req.reason) ) log.debug('[uptime] PUT request successful') return req.json()['_id']
Create a check on a given URL. Additional parameters can be used and are passed to API (for example interval, maxTime, etc). See the documentation https://github.com/fzaninotto/uptime for a full list of the parameters. CLI Example: .. code-block:: bash salt '*' uptime.create http://example.org
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/uptime.py#L32-L60
[ "def check_exists(name):\n '''\n Check if a given URL is in being monitored by uptime\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' uptime.check_exists http://example.org\n '''\n if name in checks_list():\n log.debug('[uptime] found %s in checks', name)\n return True\n return False\n", "def _get_application_url():\n '''\n Helper function to get application url from pillar\n '''\n application_url = __salt__['pillar.get']('uptime:application_url')\n if application_url is None:\n log.error('Could not load uptime:application_url pillar')\n raise CommandExecutionError(\n 'uptime:application_url pillar is required for authentication'\n )\n return application_url\n" ]
# -*- coding: utf-8 -*- ''' Wrapper around uptime API ========================= ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs from salt.exceptions import CommandExecutionError try: import requests ENABLED = True except ImportError: ENABLED = False log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if the requests python module is available ''' if ENABLED: return 'uptime' return (False, 'uptime module needs the python requests module to work') def delete(name): ''' Delete a check on a given URL CLI Example: .. code-block:: bash salt '*' uptime.delete http://example.org ''' if not check_exists(name): msg = "Trying to delete check that doesn't exists : {0}".format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug('[uptime] trying DELETE request') jcontent = requests.get('{0}/api/checks'.format(application_url)).json() url_id = [x['_id'] for x in jcontent if x['url'] == name][0] req = requests.delete('{0}/api/checks/{1}'.format(application_url, url_id)) if not req.ok: raise CommandExecutionError( 'request to uptime failed : {0}'.format(req.reason) ) log.debug('[uptime] DELETE request successful') return True def _get_application_url(): ''' Helper function to get application url from pillar ''' application_url = __salt__['pillar.get']('uptime:application_url') if application_url is None: log.error('Could not load uptime:application_url pillar') raise CommandExecutionError( 'uptime:application_url pillar is required for authentication' ) return application_url def checks_list(): ''' List URL checked by uptime CLI Example: .. code-block:: bash salt '*' uptime.checks_list ''' application_url = _get_application_url() log.debug('[uptime] get checks') jcontent = requests.get('{0}/api/checks'.format(application_url)).json() return [x['url'] for x in jcontent] def check_exists(name): ''' Check if a given URL is in being monitored by uptime CLI Example: .. code-block:: bash salt '*' uptime.check_exists http://example.org ''' if name in checks_list(): log.debug('[uptime] found %s in checks', name) return True return False
saltstack/salt
salt/modules/uptime.py
delete
python
def delete(name): ''' Delete a check on a given URL CLI Example: .. code-block:: bash salt '*' uptime.delete http://example.org ''' if not check_exists(name): msg = "Trying to delete check that doesn't exists : {0}".format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug('[uptime] trying DELETE request') jcontent = requests.get('{0}/api/checks'.format(application_url)).json() url_id = [x['_id'] for x in jcontent if x['url'] == name][0] req = requests.delete('{0}/api/checks/{1}'.format(application_url, url_id)) if not req.ok: raise CommandExecutionError( 'request to uptime failed : {0}'.format(req.reason) ) log.debug('[uptime] DELETE request successful') return True
Delete a check on a given URL CLI Example: .. code-block:: bash salt '*' uptime.delete http://example.org
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/uptime.py#L63-L87
[ "def check_exists(name):\n '''\n Check if a given URL is in being monitored by uptime\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' uptime.check_exists http://example.org\n '''\n if name in checks_list():\n log.debug('[uptime] found %s in checks', name)\n return True\n return False\n", "def _get_application_url():\n '''\n Helper function to get application url from pillar\n '''\n application_url = __salt__['pillar.get']('uptime:application_url')\n if application_url is None:\n log.error('Could not load uptime:application_url pillar')\n raise CommandExecutionError(\n 'uptime:application_url pillar is required for authentication'\n )\n return application_url\n" ]
# -*- coding: utf-8 -*- ''' Wrapper around uptime API ========================= ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs from salt.exceptions import CommandExecutionError try: import requests ENABLED = True except ImportError: ENABLED = False log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if the requests python module is available ''' if ENABLED: return 'uptime' return (False, 'uptime module needs the python requests module to work') def create(name, **params): '''Create a check on a given URL. Additional parameters can be used and are passed to API (for example interval, maxTime, etc). See the documentation https://github.com/fzaninotto/uptime for a full list of the parameters. CLI Example: .. code-block:: bash salt '*' uptime.create http://example.org ''' if check_exists(name): msg = 'Trying to create check that already exists : {0}'.format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug('[uptime] trying PUT request') params.update(url=name) req = requests.put('{0}/api/checks'.format(application_url), data=params) if not req.ok: raise CommandExecutionError( 'request to uptime failed : {0}'.format(req.reason) ) log.debug('[uptime] PUT request successful') return req.json()['_id'] def _get_application_url(): ''' Helper function to get application url from pillar ''' application_url = __salt__['pillar.get']('uptime:application_url') if application_url is None: log.error('Could not load uptime:application_url pillar') raise CommandExecutionError( 'uptime:application_url pillar is required for authentication' ) return application_url def checks_list(): ''' List URL checked by uptime CLI Example: .. code-block:: bash salt '*' uptime.checks_list ''' application_url = _get_application_url() log.debug('[uptime] get checks') jcontent = requests.get('{0}/api/checks'.format(application_url)).json() return [x['url'] for x in jcontent] def check_exists(name): ''' Check if a given URL is in being monitored by uptime CLI Example: .. code-block:: bash salt '*' uptime.check_exists http://example.org ''' if name in checks_list(): log.debug('[uptime] found %s in checks', name) return True return False
saltstack/salt
salt/modules/uptime.py
checks_list
python
def checks_list(): ''' List URL checked by uptime CLI Example: .. code-block:: bash salt '*' uptime.checks_list ''' application_url = _get_application_url() log.debug('[uptime] get checks') jcontent = requests.get('{0}/api/checks'.format(application_url)).json() return [x['url'] for x in jcontent]
List URL checked by uptime CLI Example: .. code-block:: bash salt '*' uptime.checks_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/uptime.py#L103-L116
[ "def _get_application_url():\n '''\n Helper function to get application url from pillar\n '''\n application_url = __salt__['pillar.get']('uptime:application_url')\n if application_url is None:\n log.error('Could not load uptime:application_url pillar')\n raise CommandExecutionError(\n 'uptime:application_url pillar is required for authentication'\n )\n return application_url\n" ]
# -*- coding: utf-8 -*- ''' Wrapper around uptime API ========================= ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs from salt.exceptions import CommandExecutionError try: import requests ENABLED = True except ImportError: ENABLED = False log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if the requests python module is available ''' if ENABLED: return 'uptime' return (False, 'uptime module needs the python requests module to work') def create(name, **params): '''Create a check on a given URL. Additional parameters can be used and are passed to API (for example interval, maxTime, etc). See the documentation https://github.com/fzaninotto/uptime for a full list of the parameters. CLI Example: .. code-block:: bash salt '*' uptime.create http://example.org ''' if check_exists(name): msg = 'Trying to create check that already exists : {0}'.format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug('[uptime] trying PUT request') params.update(url=name) req = requests.put('{0}/api/checks'.format(application_url), data=params) if not req.ok: raise CommandExecutionError( 'request to uptime failed : {0}'.format(req.reason) ) log.debug('[uptime] PUT request successful') return req.json()['_id'] def delete(name): ''' Delete a check on a given URL CLI Example: .. code-block:: bash salt '*' uptime.delete http://example.org ''' if not check_exists(name): msg = "Trying to delete check that doesn't exists : {0}".format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug('[uptime] trying DELETE request') jcontent = requests.get('{0}/api/checks'.format(application_url)).json() url_id = [x['_id'] for x in jcontent if x['url'] == name][0] req = requests.delete('{0}/api/checks/{1}'.format(application_url, url_id)) if not req.ok: raise CommandExecutionError( 'request to uptime failed : {0}'.format(req.reason) ) log.debug('[uptime] DELETE request successful') return True def _get_application_url(): ''' Helper function to get application url from pillar ''' application_url = __salt__['pillar.get']('uptime:application_url') if application_url is None: log.error('Could not load uptime:application_url pillar') raise CommandExecutionError( 'uptime:application_url pillar is required for authentication' ) return application_url def check_exists(name): ''' Check if a given URL is in being monitored by uptime CLI Example: .. code-block:: bash salt '*' uptime.check_exists http://example.org ''' if name in checks_list(): log.debug('[uptime] found %s in checks', name) return True return False
saltstack/salt
salt/states/acme.py
cert
python
def cert(name, aliases=None, email=None, webroot=None, test_cert=False, renew=None, keysize=None, server=None, owner='root', group='root', mode='0640', certname=None, preferred_challenges=None, tls_sni_01_port=None, tls_sni_01_address=None, http_01_port=None, http_01_address=None, dns_plugin=None, dns_plugin_credentials=None): ''' Obtain/renew a certificate from an ACME CA, probably Let's Encrypt. :param name: Common Name of the certificate (DNS name of certificate) :param aliases: subjectAltNames (Additional DNS names on certificate) :param email: e-mail address for interaction with ACME provider :param webroot: True or a full path to webroot. Otherwise use standalone mode :param test_cert: Request a certificate from the Happy Hacker Fake CA (mutually exclusive with 'server') :param renew: True/'force' to force a renewal, or a window of renewal before expiry in days :param keysize: RSA key bits :param server: API endpoint to talk to :param owner: owner of the private key file :param group: group of the private key file :param mode: mode of the private key file :param certname: Name of the certificate to save :param preferred_challenges: A sorted, comma delimited list of the preferred challenge to use during authorization with the most preferred challenge listed first. :param tls_sni_01_port: Port used during tls-sni-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 443. :param tls_sni_01_address: The address the server listens to during tls-sni-01 challenge. :param http_01_port: Port used in the http-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 80. :param https_01_address: The address the server listens to during http-01 challenge. :param dns_plugin: Name of a DNS plugin to use (currently only 'cloudflare') :param dns_plugin_credentials: Path to the credentials file if required by the specified DNS plugin ''' if __opts__['test']: ret = { 'name': name, 'changes': {}, 'result': None } window = None try: window = int(renew) except Exception: pass comment = 'Certificate {0} '.format(name) if not __salt__['acme.has'](name): comment += 'would have been obtained' elif __salt__['acme.needs_renewal'](name, window): comment += 'would have been renewed' else: comment += 'would not have been touched' ret['result'] = True ret['comment'] = comment return ret if not __salt__['acme.has'](name): old = None else: old = __salt__['acme.info'](name) res = __salt__['acme.cert']( name, aliases=aliases, email=email, webroot=webroot, certname=certname, test_cert=test_cert, renew=renew, keysize=keysize, server=server, owner=owner, group=group, mode=mode, preferred_challenges=preferred_challenges, tls_sni_01_port=tls_sni_01_port, tls_sni_01_address=tls_sni_01_address, http_01_port=http_01_port, http_01_address=http_01_address, dns_plugin=dns_plugin, dns_plugin_credentials=dns_plugin_credentials, ) ret = { 'name': name, 'result': res['result'] is not False, 'comment': res['comment'] } if res['result'] is None: ret['changes'] = {} else: if not __salt__['acme.has'](name): new = None else: new = __salt__['acme.info'](name) ret['changes'] = { 'old': old, 'new': new } return ret
Obtain/renew a certificate from an ACME CA, probably Let's Encrypt. :param name: Common Name of the certificate (DNS name of certificate) :param aliases: subjectAltNames (Additional DNS names on certificate) :param email: e-mail address for interaction with ACME provider :param webroot: True or a full path to webroot. Otherwise use standalone mode :param test_cert: Request a certificate from the Happy Hacker Fake CA (mutually exclusive with 'server') :param renew: True/'force' to force a renewal, or a window of renewal before expiry in days :param keysize: RSA key bits :param server: API endpoint to talk to :param owner: owner of the private key file :param group: group of the private key file :param mode: mode of the private key file :param certname: Name of the certificate to save :param preferred_challenges: A sorted, comma delimited list of the preferred challenge to use during authorization with the most preferred challenge listed first. :param tls_sni_01_port: Port used during tls-sni-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 443. :param tls_sni_01_address: The address the server listens to during tls-sni-01 challenge. :param http_01_port: Port used in the http-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 80. :param https_01_address: The address the server listens to during http-01 challenge. :param dns_plugin: Name of a DNS plugin to use (currently only 'cloudflare') :param dns_plugin_credentials: Path to the credentials file if required by the specified DNS plugin
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/acme.py#L42-L161
null
# -*- coding: utf-8 -*- ''' ACME / Let's Encrypt certificate management state ================================================= .. versionadded: 2016.3 See also the module documentation .. code-block:: yaml reload-gitlab: cmd.run: - name: gitlab-ctl hup dev.example.com: acme.cert: - aliases: - gitlab.example.com - email: acmemaster@example.com - webroot: /opt/gitlab/embedded/service/gitlab-rails/public - renew: 14 - fire_event: acme/dev.example.com - onchanges_in: - cmd: reload-gitlab ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging log = logging.getLogger(__name__) def __virtual__(): ''' Only work when the ACME module agrees ''' return 'acme.cert' in __salt__
saltstack/salt
salt/states/vagrant.py
_vagrant_call
python
def _vagrant_call(node, function, section, comment, status_when_done=None, **kwargs): ''' Helper to call the vagrant functions. Wildcards supported. :param node: The Salt-id or wildcard :param function: the vagrant submodule to call :param section: the name for the state call. :param comment: what the state reply should say :param status_when_done: the Vagrant status expected for this state :return: the dictionary for the state reply ''' ret = {'name': node, 'changes': {}, 'result': True, 'comment': ''} targeted_nodes = [] if isinstance(node, six.string_types): try: # use shortcut if a single node name if __salt__['vagrant.get_vm_info'](node): targeted_nodes = [node] except SaltInvocationError: pass if not targeted_nodes: # the shortcut failed, do this the hard way all_domains = __salt__['vagrant.list_domains']() targeted_nodes = fnmatch.filter(all_domains, node) changed_nodes = [] ignored_nodes = [] for node in targeted_nodes: if status_when_done: try: present_state = __salt__['vagrant.vm_state'](node)[0] if present_state['state'] == status_when_done: continue # no change is needed except (IndexError, SaltInvocationError, CommandExecutionError): pass try: response = __salt__['vagrant.{0}'.format(function)](node, **kwargs) if isinstance(response, dict): response = response['name'] changed_nodes.append({'node': node, function: response}) except (SaltInvocationError, CommandExecutionError) as err: ignored_nodes.append({'node': node, 'issue': six.text_type(err)}) if not changed_nodes: ret['result'] = True ret['comment'] = 'No changes seen' if ignored_nodes: ret['changes'] = {'ignored': ignored_nodes} else: ret['changes'] = {section: changed_nodes} ret['comment'] = comment return ret
Helper to call the vagrant functions. Wildcards supported. :param node: The Salt-id or wildcard :param function: the vagrant submodule to call :param section: the name for the state call. :param comment: what the state reply should say :param status_when_done: the Vagrant status expected for this state :return: the dictionary for the state reply
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/vagrant.py#L77-L127
null
# -*- coding: utf-8 -*- r''' Manage Vagrant VMs ================== Manange execution of Vagrant virtual machines on Salt minions. Vagrant_ is a tool for building and managing virtual machine environments. It can use various providers, such as VirtualBox_, Docker_, or VMware_, to run its VMs. Vagrant provides some of the functionality of a light-weight hypervisor. The combination of Salt modules, Vagrant running on the host, and a virtual machine provider, gives hypervisor-like functionality for developers who use Vagrant to quickly define their virtual environments. .. _Vagrant: http://www.vagrantup.com/ .. _VirtualBox: https://www.virtualbox.org/ .. _Docker: https://www.docker.io/ .. _VMWare: https://www.vmware.com/ .. versionadded:: 2018.3.0 The configuration of each virtual machine is defined in a file named ``Vagrantfile`` which must exist on the VM host machine. The essential parameters which must be defined to start a Vagrant VM are the directory where the ``Vagrantfile`` is located \(argument ``cwd:``\), and the username which will own the ``Vagrant box`` created for the VM \( argument ``vagrant_runas:``\). A single ``Vagrantfile`` may define one or more virtual machines. Use the ``machine`` argument to chose among them. The default (blank) value will select the ``primary`` (or only) machine in the Vagrantfile. \[NOTE:\] Each virtual machine host must have the following: - a working salt-minion - a Salt sdb database configured for ``vagrant_sdb_data``. - Vagrant installed and the ``vagrant`` command working - a suitable VM provider .. code-block:: yaml # EXAMPLE: # file /etc/salt/minion.d/vagrant_sdb.conf on the host computer # -- this sdb database is required by the Vagrant module -- vagrant_sdb_data: # The sdb database must have this name. driver: sqlite3 # Let's use SQLite to store the data ... database: /var/cache/salt/vagrant.sqlite # ... in this file ... table: sdb # ... using this table name. create_table: True # if not present ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import fnmatch # Import Salt libs import salt.utils.args from salt.exceptions import CommandExecutionError, SaltInvocationError import salt.ext.six as six __virtualname__ = 'vagrant' def __virtual__(): ''' Only if vagrant module is available. :return: ''' if 'vagrant.version' in __salt__: return __virtualname__ return False def running(name, **kwargs): r''' Defines and starts a new VM with specified arguments, or restart a VM (or group of VMs). (Runs ``vagrant up``.) :param name: the Salt_id node name you wish your VM to have. If ``name`` contains a "?" or "*" then it will re-start a group of VMs which have been paused or stopped. Each machine must be initially started individually using this function or the vagrant.init execution module call. \[NOTE:\] Keyword arguments are silently ignored when re-starting an existing VM. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name: vagrant.running .. code-block:: yaml node_name: vagrant.running: - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 ''' if '*' in name or '?' in name: return _vagrant_call(name, 'start', 'restarted', "Machine has been restarted", "running") else: ret = {'name': name, 'changes': {}, 'result': True, 'comment': '{0} is already running'.format(name) } try: info = __salt__['vagrant.vm_state'](name) if info[0]['state'] != 'running': __salt__['vagrant.start'](name) ret['changes'][name] = 'Machine started' ret['comment'] = 'Node {0} started'.format(name) except (SaltInvocationError, CommandExecutionError): # there was no viable existing machine to start ret, kwargs = _find_init_change(name, ret, **kwargs) kwargs['start'] = True __salt__['vagrant.init'](name, **kwargs) ret['changes'][name] = 'Node defined and started' ret['comment'] = 'Node {0} defined and started'.format(name) return ret def _find_init_change(name, ret, **kwargs): ''' look for changes from any previous init of machine. :return: modified ret and kwargs ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if 'vm' in kwargs: kwargs.update(kwargs.pop('vm')) # the state processing eats 'runas' so we rename kwargs['runas'] = kwargs.pop('vagrant_runas', '') try: vm_ = __salt__['vagrant.get_vm_info'](name) except SaltInvocationError: vm_ = {} for key, value in kwargs.items(): ret['changes'][key] = {'old': None, 'new': value} if vm_: # test for changed values for key in vm_: value = vm_[key] or '' # supply a blank if value is None if key != 'name': # will be missing in kwargs new = kwargs.get(key, '') if new != value: if key == 'machine' and new == '': continue # we don't know the default machine name ret['changes'][key] = {'old': value, 'new': new} return ret, kwargs def initialized(name, **kwargs): r''' Defines a new VM with specified arguments, but does not start it. :param name: the Salt_id node name you wish your VM to have. Each machine must be initialized individually using this function or the "vagrant.running" function, or the vagrant.init execution module call. This command will not change the state of a running or paused machine. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name1: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 node_name2: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine2 start_nodes: vagrant.start: - name: node_name? ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'The VM is already correctly defined' } # define a machine to start later ret, kwargs = _find_init_change(name, ret, **kwargs) if ret['changes'] == {}: return ret kwargs['start'] = False __salt__['vagrant.init'](name, **kwargs) ret['changes'][name] = 'Node initialized' ret['comment'] = 'Node {0} defined but not started.'.format(name) return ret def stopped(name): ''' Stops a VM (or VMs) by shutting it (them) down nicely. (Runs ``vagrant halt``) :param name: May be a Salt_id node, or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.stopped ''' return _vagrant_call(name, 'shutdown', 'stopped', 'Machine has been shut down', 'poweroff') def powered_off(name): ''' Stops a VM (or VMs) by power off. (Runs ``vagrant halt``.) This method is provided for compatibility with other VM-control state modules. For Vagrant, the action is identical with ``stopped``. :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.unpowered ''' return _vagrant_call(name, 'stop', 'unpowered', 'Machine has been powered off', 'poweroff') def destroyed(name): ''' Stops a VM (or VMs) and removes all references to it (them). (Runs ``vagrant destroy``.) Subsequent re-use of the same machine will requere another operation of ``vagrant.running`` or a call to the ``vagrant.init`` execution module. :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.destroyed ''' return _vagrant_call(name, 'destroy', 'destroyed', 'Machine has been removed') def paused(name): ''' Stores the state of a VM (or VMs) for fast restart. (Runs ``vagrant suspend``.) :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.paused ''' return _vagrant_call(name, 'pause', 'paused', 'Machine has been suspended', 'saved') def rebooted(name): ''' Reboots a running, paused, or stopped VM (or VMs). (Runs ``vagrant reload``.) The will re-run the provisioning :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.reloaded ''' return _vagrant_call(name, 'reboot', 'rebooted', 'Machine has been reloaded')
saltstack/salt
salt/states/vagrant.py
running
python
def running(name, **kwargs): r''' Defines and starts a new VM with specified arguments, or restart a VM (or group of VMs). (Runs ``vagrant up``.) :param name: the Salt_id node name you wish your VM to have. If ``name`` contains a "?" or "*" then it will re-start a group of VMs which have been paused or stopped. Each machine must be initially started individually using this function or the vagrant.init execution module call. \[NOTE:\] Keyword arguments are silently ignored when re-starting an existing VM. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name: vagrant.running .. code-block:: yaml node_name: vagrant.running: - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 ''' if '*' in name or '?' in name: return _vagrant_call(name, 'start', 'restarted', "Machine has been restarted", "running") else: ret = {'name': name, 'changes': {}, 'result': True, 'comment': '{0} is already running'.format(name) } try: info = __salt__['vagrant.vm_state'](name) if info[0]['state'] != 'running': __salt__['vagrant.start'](name) ret['changes'][name] = 'Machine started' ret['comment'] = 'Node {0} started'.format(name) except (SaltInvocationError, CommandExecutionError): # there was no viable existing machine to start ret, kwargs = _find_init_change(name, ret, **kwargs) kwargs['start'] = True __salt__['vagrant.init'](name, **kwargs) ret['changes'][name] = 'Node defined and started' ret['comment'] = 'Node {0} defined and started'.format(name) return ret
r''' Defines and starts a new VM with specified arguments, or restart a VM (or group of VMs). (Runs ``vagrant up``.) :param name: the Salt_id node name you wish your VM to have. If ``name`` contains a "?" or "*" then it will re-start a group of VMs which have been paused or stopped. Each machine must be initially started individually using this function or the vagrant.init execution module call. \[NOTE:\] Keyword arguments are silently ignored when re-starting an existing VM. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name: vagrant.running .. code-block:: yaml node_name: vagrant.running: - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/vagrant.py#L130-L194
[ "def _vagrant_call(node, function, section, comment, status_when_done=None, **kwargs):\n '''\n Helper to call the vagrant functions. Wildcards supported.\n\n :param node: The Salt-id or wildcard\n :param function: the vagrant submodule to call\n :param section: the name for the state call.\n :param comment: what the state reply should say\n :param status_when_done: the Vagrant status expected for this state\n :return: the dictionary for the state reply\n '''\n ret = {'name': node, 'changes': {}, 'result': True, 'comment': ''}\n\n targeted_nodes = []\n if isinstance(node, six.string_types):\n try: # use shortcut if a single node name\n if __salt__['vagrant.get_vm_info'](node):\n targeted_nodes = [node]\n except SaltInvocationError:\n pass\n\n if not targeted_nodes: # the shortcut failed, do this the hard way\n all_domains = __salt__['vagrant.list_domains']()\n targeted_nodes = fnmatch.filter(all_domains, node)\n changed_nodes = []\n ignored_nodes = []\n for node in targeted_nodes:\n if status_when_done:\n try:\n present_state = __salt__['vagrant.vm_state'](node)[0]\n if present_state['state'] == status_when_done:\n continue # no change is needed\n except (IndexError, SaltInvocationError, CommandExecutionError):\n pass\n try:\n response = __salt__['vagrant.{0}'.format(function)](node, **kwargs)\n if isinstance(response, dict):\n response = response['name']\n changed_nodes.append({'node': node, function: response})\n except (SaltInvocationError, CommandExecutionError) as err:\n ignored_nodes.append({'node': node, 'issue': six.text_type(err)})\n if not changed_nodes:\n ret['result'] = True\n ret['comment'] = 'No changes seen'\n if ignored_nodes:\n ret['changes'] = {'ignored': ignored_nodes}\n else:\n ret['changes'] = {section: changed_nodes}\n ret['comment'] = comment\n\n return ret\n", "def _find_init_change(name, ret, **kwargs):\n '''\n look for changes from any previous init of machine.\n\n :return: modified ret and kwargs\n '''\n kwargs = salt.utils.args.clean_kwargs(**kwargs)\n if 'vm' in kwargs:\n kwargs.update(kwargs.pop('vm'))\n # the state processing eats 'runas' so we rename\n kwargs['runas'] = kwargs.pop('vagrant_runas', '')\n try:\n vm_ = __salt__['vagrant.get_vm_info'](name)\n except SaltInvocationError:\n vm_ = {}\n for key, value in kwargs.items():\n ret['changes'][key] = {'old': None, 'new': value}\n if vm_: # test for changed values\n for key in vm_:\n value = vm_[key] or '' # supply a blank if value is None\n if key != 'name': # will be missing in kwargs\n new = kwargs.get(key, '')\n if new != value:\n if key == 'machine' and new == '':\n continue # we don't know the default machine name\n ret['changes'][key] = {'old': value, 'new': new}\n return ret, kwargs\n" ]
# -*- coding: utf-8 -*- r''' Manage Vagrant VMs ================== Manange execution of Vagrant virtual machines on Salt minions. Vagrant_ is a tool for building and managing virtual machine environments. It can use various providers, such as VirtualBox_, Docker_, or VMware_, to run its VMs. Vagrant provides some of the functionality of a light-weight hypervisor. The combination of Salt modules, Vagrant running on the host, and a virtual machine provider, gives hypervisor-like functionality for developers who use Vagrant to quickly define their virtual environments. .. _Vagrant: http://www.vagrantup.com/ .. _VirtualBox: https://www.virtualbox.org/ .. _Docker: https://www.docker.io/ .. _VMWare: https://www.vmware.com/ .. versionadded:: 2018.3.0 The configuration of each virtual machine is defined in a file named ``Vagrantfile`` which must exist on the VM host machine. The essential parameters which must be defined to start a Vagrant VM are the directory where the ``Vagrantfile`` is located \(argument ``cwd:``\), and the username which will own the ``Vagrant box`` created for the VM \( argument ``vagrant_runas:``\). A single ``Vagrantfile`` may define one or more virtual machines. Use the ``machine`` argument to chose among them. The default (blank) value will select the ``primary`` (or only) machine in the Vagrantfile. \[NOTE:\] Each virtual machine host must have the following: - a working salt-minion - a Salt sdb database configured for ``vagrant_sdb_data``. - Vagrant installed and the ``vagrant`` command working - a suitable VM provider .. code-block:: yaml # EXAMPLE: # file /etc/salt/minion.d/vagrant_sdb.conf on the host computer # -- this sdb database is required by the Vagrant module -- vagrant_sdb_data: # The sdb database must have this name. driver: sqlite3 # Let's use SQLite to store the data ... database: /var/cache/salt/vagrant.sqlite # ... in this file ... table: sdb # ... using this table name. create_table: True # if not present ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import fnmatch # Import Salt libs import salt.utils.args from salt.exceptions import CommandExecutionError, SaltInvocationError import salt.ext.six as six __virtualname__ = 'vagrant' def __virtual__(): ''' Only if vagrant module is available. :return: ''' if 'vagrant.version' in __salt__: return __virtualname__ return False def _vagrant_call(node, function, section, comment, status_when_done=None, **kwargs): ''' Helper to call the vagrant functions. Wildcards supported. :param node: The Salt-id or wildcard :param function: the vagrant submodule to call :param section: the name for the state call. :param comment: what the state reply should say :param status_when_done: the Vagrant status expected for this state :return: the dictionary for the state reply ''' ret = {'name': node, 'changes': {}, 'result': True, 'comment': ''} targeted_nodes = [] if isinstance(node, six.string_types): try: # use shortcut if a single node name if __salt__['vagrant.get_vm_info'](node): targeted_nodes = [node] except SaltInvocationError: pass if not targeted_nodes: # the shortcut failed, do this the hard way all_domains = __salt__['vagrant.list_domains']() targeted_nodes = fnmatch.filter(all_domains, node) changed_nodes = [] ignored_nodes = [] for node in targeted_nodes: if status_when_done: try: present_state = __salt__['vagrant.vm_state'](node)[0] if present_state['state'] == status_when_done: continue # no change is needed except (IndexError, SaltInvocationError, CommandExecutionError): pass try: response = __salt__['vagrant.{0}'.format(function)](node, **kwargs) if isinstance(response, dict): response = response['name'] changed_nodes.append({'node': node, function: response}) except (SaltInvocationError, CommandExecutionError) as err: ignored_nodes.append({'node': node, 'issue': six.text_type(err)}) if not changed_nodes: ret['result'] = True ret['comment'] = 'No changes seen' if ignored_nodes: ret['changes'] = {'ignored': ignored_nodes} else: ret['changes'] = {section: changed_nodes} ret['comment'] = comment return ret def _find_init_change(name, ret, **kwargs): ''' look for changes from any previous init of machine. :return: modified ret and kwargs ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if 'vm' in kwargs: kwargs.update(kwargs.pop('vm')) # the state processing eats 'runas' so we rename kwargs['runas'] = kwargs.pop('vagrant_runas', '') try: vm_ = __salt__['vagrant.get_vm_info'](name) except SaltInvocationError: vm_ = {} for key, value in kwargs.items(): ret['changes'][key] = {'old': None, 'new': value} if vm_: # test for changed values for key in vm_: value = vm_[key] or '' # supply a blank if value is None if key != 'name': # will be missing in kwargs new = kwargs.get(key, '') if new != value: if key == 'machine' and new == '': continue # we don't know the default machine name ret['changes'][key] = {'old': value, 'new': new} return ret, kwargs def initialized(name, **kwargs): r''' Defines a new VM with specified arguments, but does not start it. :param name: the Salt_id node name you wish your VM to have. Each machine must be initialized individually using this function or the "vagrant.running" function, or the vagrant.init execution module call. This command will not change the state of a running or paused machine. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name1: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 node_name2: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine2 start_nodes: vagrant.start: - name: node_name? ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'The VM is already correctly defined' } # define a machine to start later ret, kwargs = _find_init_change(name, ret, **kwargs) if ret['changes'] == {}: return ret kwargs['start'] = False __salt__['vagrant.init'](name, **kwargs) ret['changes'][name] = 'Node initialized' ret['comment'] = 'Node {0} defined but not started.'.format(name) return ret def stopped(name): ''' Stops a VM (or VMs) by shutting it (them) down nicely. (Runs ``vagrant halt``) :param name: May be a Salt_id node, or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.stopped ''' return _vagrant_call(name, 'shutdown', 'stopped', 'Machine has been shut down', 'poweroff') def powered_off(name): ''' Stops a VM (or VMs) by power off. (Runs ``vagrant halt``.) This method is provided for compatibility with other VM-control state modules. For Vagrant, the action is identical with ``stopped``. :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.unpowered ''' return _vagrant_call(name, 'stop', 'unpowered', 'Machine has been powered off', 'poweroff') def destroyed(name): ''' Stops a VM (or VMs) and removes all references to it (them). (Runs ``vagrant destroy``.) Subsequent re-use of the same machine will requere another operation of ``vagrant.running`` or a call to the ``vagrant.init`` execution module. :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.destroyed ''' return _vagrant_call(name, 'destroy', 'destroyed', 'Machine has been removed') def paused(name): ''' Stores the state of a VM (or VMs) for fast restart. (Runs ``vagrant suspend``.) :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.paused ''' return _vagrant_call(name, 'pause', 'paused', 'Machine has been suspended', 'saved') def rebooted(name): ''' Reboots a running, paused, or stopped VM (or VMs). (Runs ``vagrant reload``.) The will re-run the provisioning :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.reloaded ''' return _vagrant_call(name, 'reboot', 'rebooted', 'Machine has been reloaded')
saltstack/salt
salt/states/vagrant.py
_find_init_change
python
def _find_init_change(name, ret, **kwargs): ''' look for changes from any previous init of machine. :return: modified ret and kwargs ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if 'vm' in kwargs: kwargs.update(kwargs.pop('vm')) # the state processing eats 'runas' so we rename kwargs['runas'] = kwargs.pop('vagrant_runas', '') try: vm_ = __salt__['vagrant.get_vm_info'](name) except SaltInvocationError: vm_ = {} for key, value in kwargs.items(): ret['changes'][key] = {'old': None, 'new': value} if vm_: # test for changed values for key in vm_: value = vm_[key] or '' # supply a blank if value is None if key != 'name': # will be missing in kwargs new = kwargs.get(key, '') if new != value: if key == 'machine' and new == '': continue # we don't know the default machine name ret['changes'][key] = {'old': value, 'new': new} return ret, kwargs
look for changes from any previous init of machine. :return: modified ret and kwargs
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/vagrant.py#L197-L223
[ "def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n" ]
# -*- coding: utf-8 -*- r''' Manage Vagrant VMs ================== Manange execution of Vagrant virtual machines on Salt minions. Vagrant_ is a tool for building and managing virtual machine environments. It can use various providers, such as VirtualBox_, Docker_, or VMware_, to run its VMs. Vagrant provides some of the functionality of a light-weight hypervisor. The combination of Salt modules, Vagrant running on the host, and a virtual machine provider, gives hypervisor-like functionality for developers who use Vagrant to quickly define their virtual environments. .. _Vagrant: http://www.vagrantup.com/ .. _VirtualBox: https://www.virtualbox.org/ .. _Docker: https://www.docker.io/ .. _VMWare: https://www.vmware.com/ .. versionadded:: 2018.3.0 The configuration of each virtual machine is defined in a file named ``Vagrantfile`` which must exist on the VM host machine. The essential parameters which must be defined to start a Vagrant VM are the directory where the ``Vagrantfile`` is located \(argument ``cwd:``\), and the username which will own the ``Vagrant box`` created for the VM \( argument ``vagrant_runas:``\). A single ``Vagrantfile`` may define one or more virtual machines. Use the ``machine`` argument to chose among them. The default (blank) value will select the ``primary`` (or only) machine in the Vagrantfile. \[NOTE:\] Each virtual machine host must have the following: - a working salt-minion - a Salt sdb database configured for ``vagrant_sdb_data``. - Vagrant installed and the ``vagrant`` command working - a suitable VM provider .. code-block:: yaml # EXAMPLE: # file /etc/salt/minion.d/vagrant_sdb.conf on the host computer # -- this sdb database is required by the Vagrant module -- vagrant_sdb_data: # The sdb database must have this name. driver: sqlite3 # Let's use SQLite to store the data ... database: /var/cache/salt/vagrant.sqlite # ... in this file ... table: sdb # ... using this table name. create_table: True # if not present ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import fnmatch # Import Salt libs import salt.utils.args from salt.exceptions import CommandExecutionError, SaltInvocationError import salt.ext.six as six __virtualname__ = 'vagrant' def __virtual__(): ''' Only if vagrant module is available. :return: ''' if 'vagrant.version' in __salt__: return __virtualname__ return False def _vagrant_call(node, function, section, comment, status_when_done=None, **kwargs): ''' Helper to call the vagrant functions. Wildcards supported. :param node: The Salt-id or wildcard :param function: the vagrant submodule to call :param section: the name for the state call. :param comment: what the state reply should say :param status_when_done: the Vagrant status expected for this state :return: the dictionary for the state reply ''' ret = {'name': node, 'changes': {}, 'result': True, 'comment': ''} targeted_nodes = [] if isinstance(node, six.string_types): try: # use shortcut if a single node name if __salt__['vagrant.get_vm_info'](node): targeted_nodes = [node] except SaltInvocationError: pass if not targeted_nodes: # the shortcut failed, do this the hard way all_domains = __salt__['vagrant.list_domains']() targeted_nodes = fnmatch.filter(all_domains, node) changed_nodes = [] ignored_nodes = [] for node in targeted_nodes: if status_when_done: try: present_state = __salt__['vagrant.vm_state'](node)[0] if present_state['state'] == status_when_done: continue # no change is needed except (IndexError, SaltInvocationError, CommandExecutionError): pass try: response = __salt__['vagrant.{0}'.format(function)](node, **kwargs) if isinstance(response, dict): response = response['name'] changed_nodes.append({'node': node, function: response}) except (SaltInvocationError, CommandExecutionError) as err: ignored_nodes.append({'node': node, 'issue': six.text_type(err)}) if not changed_nodes: ret['result'] = True ret['comment'] = 'No changes seen' if ignored_nodes: ret['changes'] = {'ignored': ignored_nodes} else: ret['changes'] = {section: changed_nodes} ret['comment'] = comment return ret def running(name, **kwargs): r''' Defines and starts a new VM with specified arguments, or restart a VM (or group of VMs). (Runs ``vagrant up``.) :param name: the Salt_id node name you wish your VM to have. If ``name`` contains a "?" or "*" then it will re-start a group of VMs which have been paused or stopped. Each machine must be initially started individually using this function or the vagrant.init execution module call. \[NOTE:\] Keyword arguments are silently ignored when re-starting an existing VM. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name: vagrant.running .. code-block:: yaml node_name: vagrant.running: - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 ''' if '*' in name or '?' in name: return _vagrant_call(name, 'start', 'restarted', "Machine has been restarted", "running") else: ret = {'name': name, 'changes': {}, 'result': True, 'comment': '{0} is already running'.format(name) } try: info = __salt__['vagrant.vm_state'](name) if info[0]['state'] != 'running': __salt__['vagrant.start'](name) ret['changes'][name] = 'Machine started' ret['comment'] = 'Node {0} started'.format(name) except (SaltInvocationError, CommandExecutionError): # there was no viable existing machine to start ret, kwargs = _find_init_change(name, ret, **kwargs) kwargs['start'] = True __salt__['vagrant.init'](name, **kwargs) ret['changes'][name] = 'Node defined and started' ret['comment'] = 'Node {0} defined and started'.format(name) return ret def initialized(name, **kwargs): r''' Defines a new VM with specified arguments, but does not start it. :param name: the Salt_id node name you wish your VM to have. Each machine must be initialized individually using this function or the "vagrant.running" function, or the vagrant.init execution module call. This command will not change the state of a running or paused machine. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name1: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 node_name2: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine2 start_nodes: vagrant.start: - name: node_name? ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'The VM is already correctly defined' } # define a machine to start later ret, kwargs = _find_init_change(name, ret, **kwargs) if ret['changes'] == {}: return ret kwargs['start'] = False __salt__['vagrant.init'](name, **kwargs) ret['changes'][name] = 'Node initialized' ret['comment'] = 'Node {0} defined but not started.'.format(name) return ret def stopped(name): ''' Stops a VM (or VMs) by shutting it (them) down nicely. (Runs ``vagrant halt``) :param name: May be a Salt_id node, or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.stopped ''' return _vagrant_call(name, 'shutdown', 'stopped', 'Machine has been shut down', 'poweroff') def powered_off(name): ''' Stops a VM (or VMs) by power off. (Runs ``vagrant halt``.) This method is provided for compatibility with other VM-control state modules. For Vagrant, the action is identical with ``stopped``. :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.unpowered ''' return _vagrant_call(name, 'stop', 'unpowered', 'Machine has been powered off', 'poweroff') def destroyed(name): ''' Stops a VM (or VMs) and removes all references to it (them). (Runs ``vagrant destroy``.) Subsequent re-use of the same machine will requere another operation of ``vagrant.running`` or a call to the ``vagrant.init`` execution module. :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.destroyed ''' return _vagrant_call(name, 'destroy', 'destroyed', 'Machine has been removed') def paused(name): ''' Stores the state of a VM (or VMs) for fast restart. (Runs ``vagrant suspend``.) :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.paused ''' return _vagrant_call(name, 'pause', 'paused', 'Machine has been suspended', 'saved') def rebooted(name): ''' Reboots a running, paused, or stopped VM (or VMs). (Runs ``vagrant reload``.) The will re-run the provisioning :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.reloaded ''' return _vagrant_call(name, 'reboot', 'rebooted', 'Machine has been reloaded')
saltstack/salt
salt/states/vagrant.py
initialized
python
def initialized(name, **kwargs): r''' Defines a new VM with specified arguments, but does not start it. :param name: the Salt_id node name you wish your VM to have. Each machine must be initialized individually using this function or the "vagrant.running" function, or the vagrant.init execution module call. This command will not change the state of a running or paused machine. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name1: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 node_name2: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine2 start_nodes: vagrant.start: - name: node_name? ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'The VM is already correctly defined' } # define a machine to start later ret, kwargs = _find_init_change(name, ret, **kwargs) if ret['changes'] == {}: return ret kwargs['start'] = False __salt__['vagrant.init'](name, **kwargs) ret['changes'][name] = 'Node initialized' ret['comment'] = 'Node {0} defined but not started.'.format(name) return ret
r''' Defines a new VM with specified arguments, but does not start it. :param name: the Salt_id node name you wish your VM to have. Each machine must be initialized individually using this function or the "vagrant.running" function, or the vagrant.init execution module call. This command will not change the state of a running or paused machine. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name1: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 node_name2: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine2 start_nodes: vagrant.start: - name: node_name?
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/vagrant.py#L226-L280
[ "def _find_init_change(name, ret, **kwargs):\n '''\n look for changes from any previous init of machine.\n\n :return: modified ret and kwargs\n '''\n kwargs = salt.utils.args.clean_kwargs(**kwargs)\n if 'vm' in kwargs:\n kwargs.update(kwargs.pop('vm'))\n # the state processing eats 'runas' so we rename\n kwargs['runas'] = kwargs.pop('vagrant_runas', '')\n try:\n vm_ = __salt__['vagrant.get_vm_info'](name)\n except SaltInvocationError:\n vm_ = {}\n for key, value in kwargs.items():\n ret['changes'][key] = {'old': None, 'new': value}\n if vm_: # test for changed values\n for key in vm_:\n value = vm_[key] or '' # supply a blank if value is None\n if key != 'name': # will be missing in kwargs\n new = kwargs.get(key, '')\n if new != value:\n if key == 'machine' and new == '':\n continue # we don't know the default machine name\n ret['changes'][key] = {'old': value, 'new': new}\n return ret, kwargs\n" ]
# -*- coding: utf-8 -*- r''' Manage Vagrant VMs ================== Manange execution of Vagrant virtual machines on Salt minions. Vagrant_ is a tool for building and managing virtual machine environments. It can use various providers, such as VirtualBox_, Docker_, or VMware_, to run its VMs. Vagrant provides some of the functionality of a light-weight hypervisor. The combination of Salt modules, Vagrant running on the host, and a virtual machine provider, gives hypervisor-like functionality for developers who use Vagrant to quickly define their virtual environments. .. _Vagrant: http://www.vagrantup.com/ .. _VirtualBox: https://www.virtualbox.org/ .. _Docker: https://www.docker.io/ .. _VMWare: https://www.vmware.com/ .. versionadded:: 2018.3.0 The configuration of each virtual machine is defined in a file named ``Vagrantfile`` which must exist on the VM host machine. The essential parameters which must be defined to start a Vagrant VM are the directory where the ``Vagrantfile`` is located \(argument ``cwd:``\), and the username which will own the ``Vagrant box`` created for the VM \( argument ``vagrant_runas:``\). A single ``Vagrantfile`` may define one or more virtual machines. Use the ``machine`` argument to chose among them. The default (blank) value will select the ``primary`` (or only) machine in the Vagrantfile. \[NOTE:\] Each virtual machine host must have the following: - a working salt-minion - a Salt sdb database configured for ``vagrant_sdb_data``. - Vagrant installed and the ``vagrant`` command working - a suitable VM provider .. code-block:: yaml # EXAMPLE: # file /etc/salt/minion.d/vagrant_sdb.conf on the host computer # -- this sdb database is required by the Vagrant module -- vagrant_sdb_data: # The sdb database must have this name. driver: sqlite3 # Let's use SQLite to store the data ... database: /var/cache/salt/vagrant.sqlite # ... in this file ... table: sdb # ... using this table name. create_table: True # if not present ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import fnmatch # Import Salt libs import salt.utils.args from salt.exceptions import CommandExecutionError, SaltInvocationError import salt.ext.six as six __virtualname__ = 'vagrant' def __virtual__(): ''' Only if vagrant module is available. :return: ''' if 'vagrant.version' in __salt__: return __virtualname__ return False def _vagrant_call(node, function, section, comment, status_when_done=None, **kwargs): ''' Helper to call the vagrant functions. Wildcards supported. :param node: The Salt-id or wildcard :param function: the vagrant submodule to call :param section: the name for the state call. :param comment: what the state reply should say :param status_when_done: the Vagrant status expected for this state :return: the dictionary for the state reply ''' ret = {'name': node, 'changes': {}, 'result': True, 'comment': ''} targeted_nodes = [] if isinstance(node, six.string_types): try: # use shortcut if a single node name if __salt__['vagrant.get_vm_info'](node): targeted_nodes = [node] except SaltInvocationError: pass if not targeted_nodes: # the shortcut failed, do this the hard way all_domains = __salt__['vagrant.list_domains']() targeted_nodes = fnmatch.filter(all_domains, node) changed_nodes = [] ignored_nodes = [] for node in targeted_nodes: if status_when_done: try: present_state = __salt__['vagrant.vm_state'](node)[0] if present_state['state'] == status_when_done: continue # no change is needed except (IndexError, SaltInvocationError, CommandExecutionError): pass try: response = __salt__['vagrant.{0}'.format(function)](node, **kwargs) if isinstance(response, dict): response = response['name'] changed_nodes.append({'node': node, function: response}) except (SaltInvocationError, CommandExecutionError) as err: ignored_nodes.append({'node': node, 'issue': six.text_type(err)}) if not changed_nodes: ret['result'] = True ret['comment'] = 'No changes seen' if ignored_nodes: ret['changes'] = {'ignored': ignored_nodes} else: ret['changes'] = {section: changed_nodes} ret['comment'] = comment return ret def running(name, **kwargs): r''' Defines and starts a new VM with specified arguments, or restart a VM (or group of VMs). (Runs ``vagrant up``.) :param name: the Salt_id node name you wish your VM to have. If ``name`` contains a "?" or "*" then it will re-start a group of VMs which have been paused or stopped. Each machine must be initially started individually using this function or the vagrant.init execution module call. \[NOTE:\] Keyword arguments are silently ignored when re-starting an existing VM. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name: vagrant.running .. code-block:: yaml node_name: vagrant.running: - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 ''' if '*' in name or '?' in name: return _vagrant_call(name, 'start', 'restarted', "Machine has been restarted", "running") else: ret = {'name': name, 'changes': {}, 'result': True, 'comment': '{0} is already running'.format(name) } try: info = __salt__['vagrant.vm_state'](name) if info[0]['state'] != 'running': __salt__['vagrant.start'](name) ret['changes'][name] = 'Machine started' ret['comment'] = 'Node {0} started'.format(name) except (SaltInvocationError, CommandExecutionError): # there was no viable existing machine to start ret, kwargs = _find_init_change(name, ret, **kwargs) kwargs['start'] = True __salt__['vagrant.init'](name, **kwargs) ret['changes'][name] = 'Node defined and started' ret['comment'] = 'Node {0} defined and started'.format(name) return ret def _find_init_change(name, ret, **kwargs): ''' look for changes from any previous init of machine. :return: modified ret and kwargs ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if 'vm' in kwargs: kwargs.update(kwargs.pop('vm')) # the state processing eats 'runas' so we rename kwargs['runas'] = kwargs.pop('vagrant_runas', '') try: vm_ = __salt__['vagrant.get_vm_info'](name) except SaltInvocationError: vm_ = {} for key, value in kwargs.items(): ret['changes'][key] = {'old': None, 'new': value} if vm_: # test for changed values for key in vm_: value = vm_[key] or '' # supply a blank if value is None if key != 'name': # will be missing in kwargs new = kwargs.get(key, '') if new != value: if key == 'machine' and new == '': continue # we don't know the default machine name ret['changes'][key] = {'old': value, 'new': new} return ret, kwargs def stopped(name): ''' Stops a VM (or VMs) by shutting it (them) down nicely. (Runs ``vagrant halt``) :param name: May be a Salt_id node, or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.stopped ''' return _vagrant_call(name, 'shutdown', 'stopped', 'Machine has been shut down', 'poweroff') def powered_off(name): ''' Stops a VM (or VMs) by power off. (Runs ``vagrant halt``.) This method is provided for compatibility with other VM-control state modules. For Vagrant, the action is identical with ``stopped``. :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.unpowered ''' return _vagrant_call(name, 'stop', 'unpowered', 'Machine has been powered off', 'poweroff') def destroyed(name): ''' Stops a VM (or VMs) and removes all references to it (them). (Runs ``vagrant destroy``.) Subsequent re-use of the same machine will requere another operation of ``vagrant.running`` or a call to the ``vagrant.init`` execution module. :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.destroyed ''' return _vagrant_call(name, 'destroy', 'destroyed', 'Machine has been removed') def paused(name): ''' Stores the state of a VM (or VMs) for fast restart. (Runs ``vagrant suspend``.) :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.paused ''' return _vagrant_call(name, 'pause', 'paused', 'Machine has been suspended', 'saved') def rebooted(name): ''' Reboots a running, paused, or stopped VM (or VMs). (Runs ``vagrant reload``.) The will re-run the provisioning :param name: May be a Salt_id node or a POSIX-style wildcard string. .. code-block:: yaml node_name: vagrant.reloaded ''' return _vagrant_call(name, 'reboot', 'rebooted', 'Machine has been reloaded')
saltstack/salt
salt/modules/pw_user.py
_get_gecos
python
def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' try: gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) except KeyError: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 4: gecos_field.append('') return {'fullname': salt.utils.data.decode(gecos_field[0]), 'roomnumber': salt.utils.data.decode(gecos_field[1]), 'workphone': salt.utils.data.decode(gecos_field[2]), 'homephone': salt.utils.data.decode(gecos_field[3])}
Retrieve GECOS field info and return it in dictionary form
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L70-L89
null
# -*- coding: utf-8 -*- ''' Manage users with the pw command .. important:: If you feel that Salt should be using this module to manage users on a minion, and it is using a different module (or gives an error similar to *'user.info' is not available*), see :ref:`here <module-provider-override>`. ''' # Notes: # ------ # # Format of the master.passwd file: # # - name User's login name. # - password User's encrypted password. # - uid User's id. # - gid User's login group id. # - class User's login class. # - change Password change time. # - expire Account expiration time. # - gecos General information about the user. # - home_dir User's home directory. # - shell User's login shell. # # The usershow command allows viewing of an account in a format that is # identical to the format used in /etc/master.passwd (with the password field # replaced with a ‘*’.) # # Example: # % pw usershow -n someuser # someuser:*:1001:1001::0:0:SomeUser Name:/home/someuser:/bin/sh # Import python libs from __future__ import absolute_import, unicode_literals, print_function import copy import logging try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False # Import 3rd party libs from salt.ext import six # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.user from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'user' def __virtual__(): ''' Set the user module if the kernel is FreeBSD or DragonFly ''' if HAS_PWD and __grains__['kernel'] in ('FreeBSD', 'DragonFly'): return __virtualname__ return (False, 'The pw_user execution module cannot be loaded: the pwd python module is not available or the system is not FreeBSD.') def _build_gecos(gecos_dict): ''' Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with pw usermod. ''' return u'{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''), gecos_dict.get('roomnumber', ''), gecos_dict.get('workphone', ''), gecos_dict.get('homephone', '')) def _update_gecos(name, key, value): ''' Common code to change a user's GECOS information ''' if not isinstance(value, six.string_types): value = six.text_type(value) pre_info = _get_gecos(name) if not pre_info: return False if value == pre_info[key]: return True gecos_data = copy.deepcopy(pre_info) gecos_data[key] = value cmd = ['pw', 'usermod', name, '-c', _build_gecos(gecos_data)] __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) return _get_gecos(name).get(key) == value def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, fullname='', roomnumber='', workphone='', homephone='', createhome=True, loginclass=None, **kwargs): ''' Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if salt.utils.data.is_true(kwargs.pop('system', False)): log.warning('pw_user module does not support the \'system\' argument') if kwargs: log.warning('Invalid kwargs passed to user.add') if isinstance(groups, six.string_types): groups = groups.split(',') cmd = ['pw', 'useradd'] if uid: cmd.extend(['-u', uid]) if gid: cmd.extend(['-g', gid]) if groups: cmd.extend(['-G', ','.join(groups)]) if home is not None: cmd.extend(['-d', home]) if createhome is True: cmd.append('-m') if loginclass: cmd.extend(['-L', loginclass]) if shell: cmd.extend(['-s', shell]) if not salt.utils.data.is_true(unique): cmd.append('-o') gecos_field = _build_gecos({'fullname': fullname, 'roomnumber': roomnumber, 'workphone': workphone, 'homephone': homephone}) cmd.extend(['-c', gecos_field]) cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def delete(name, remove=False, force=False): ''' Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' if salt.utils.data.is_true(force): log.error('pw userdel does not support force-deleting user while ' 'user is logged in') cmd = ['pw', 'userdel'] if remove: cmd.append('-r') cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def getent(refresh=False): ''' Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] for data in pwd.getpwall(): ret.append(info(data.pw_name)) __context__['user.getent'] = ret return ret def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if uid == pre_info['uid']: return True cmd = ['pw', 'usermod', '-u', uid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('uid') == uid def chgid(name, gid): ''' Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if gid == pre_info['gid']: return True cmd = ['pw', 'usermod', '-g', gid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('gid') == gid def chshell(name, shell): ''' Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if shell == pre_info['shell']: return True cmd = ['pw', 'usermod', '-s', shell, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('shell') == shell def chhome(name, home, persist=False): ''' Set a new home directory for an existing user name Username to modify home New home directory to set persist : False Set to ``True`` to prevent configuration files in the new home directory from being overwritten by the files from the skeleton directory. CLI Example: .. code-block:: bash salt '*' user.chhome foo /home/users/foo True ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if home == pre_info['home']: return True cmd = ['pw', 'usermod', name, '-d', home] if persist: cmd.append('-m') __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('home') == home def chgroups(name, groups, append=False): ''' Change the groups to which a user belongs name Username to modify groups List of groups to set for the user. Can be passed as a comma-separated list or a Python list. append : False Set to ``True`` to append these groups to the user's existing list of groups. Otherwise, the specified groups will replace any existing groups for the user. CLI Example: .. code-block:: bash salt '*' user.chgroups foo wheel,root True ''' if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if ugrps == set(groups): return True if append: groups += ugrps cmd = ['pw', 'usermod', '-G', ','.join(groups), '-n', name] return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def chfullname(name, fullname): ''' Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo "Foo Bar" ''' return _update_gecos(name, 'fullname', fullname) def chroomnumber(name, roomnumber): ''' Change the user's Room Number CLI Example: .. code-block:: bash salt '*' user.chroomnumber foo 123 ''' return _update_gecos(name, 'roomnumber', roomnumber) def chworkphone(name, workphone): ''' Change the user's Work Phone CLI Example: .. code-block:: bash salt '*' user.chworkphone foo "7735550123" ''' return _update_gecos(name, 'workphone', workphone) def chhomephone(name, homephone): ''' Change the user's Home Phone CLI Example: .. code-block:: bash salt '*' user.chhomephone foo "7735551234" ''' return _update_gecos(name, 'homephone', homephone) def chloginclass(name, loginclass, root=None): ''' Change the default login class of the user .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff ''' if loginclass == get_loginclass(name): return True cmd = ['pw', 'usermod', '-L', '{0}'.format(loginclass), '-n', '{0}'.format(name)] __salt__['cmd.run'](cmd, python_shell=False) return get_loginclass(name) == loginclass def info(name): ''' Return user information CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} try: data = pwd.getpwnam(name) ret['gid'] = data.pw_gid ret['groups'] = list_groups(name) ret['home'] = data.pw_dir ret['name'] = data.pw_name ret['passwd'] = data.pw_passwd ret['shell'] = data.pw_shell ret['uid'] = data.pw_uid # Put GECOS info into a list gecos_field = data.pw_gecos.split(',', 3) # Assign empty strings for any unspecified GECOS fields while len(gecos_field) < 4: gecos_field.append('') ret['fullname'] = gecos_field[0] ret['roomnumber'] = gecos_field[1] ret['workphone'] = gecos_field[2] ret['homephone'] = gecos_field[3] except KeyError: return {} return ret def get_loginclass(name): ''' Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' userinfo = __salt__['cmd.run_stdout'](['pw', 'usershow', '-n', name]) userinfo = userinfo.split(':') return userinfo[4] if len(userinfo) == 10 else '' def list_groups(name): ''' Return a list of groups the named user belongs to CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' return salt.utils.user.get_group_list(name) def list_users(): ''' Return a list of all users CLI Example: .. code-block:: bash salt '*' user.list_users ''' return sorted([user.pw_name for user in pwd.getpwall()]) def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info = info(new_name) if new_info: raise CommandExecutionError( 'User \'{0}\' already exists'.format(new_name) ) cmd = ['pw', 'usermod', '-l', new_name, '-n', name] __salt__['cmd.run'](cmd) post_info = info(new_name) if post_info['name'] != current_info['name']: return post_info['name'] == new_name return False
saltstack/salt
salt/modules/pw_user.py
add
python
def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, fullname='', roomnumber='', workphone='', homephone='', createhome=True, loginclass=None, **kwargs): ''' Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if salt.utils.data.is_true(kwargs.pop('system', False)): log.warning('pw_user module does not support the \'system\' argument') if kwargs: log.warning('Invalid kwargs passed to user.add') if isinstance(groups, six.string_types): groups = groups.split(',') cmd = ['pw', 'useradd'] if uid: cmd.extend(['-u', uid]) if gid: cmd.extend(['-g', gid]) if groups: cmd.extend(['-G', ','.join(groups)]) if home is not None: cmd.extend(['-d', home]) if createhome is True: cmd.append('-m') if loginclass: cmd.extend(['-L', loginclass]) if shell: cmd.extend(['-s', shell]) if not salt.utils.data.is_true(unique): cmd.append('-o') gecos_field = _build_gecos({'fullname': fullname, 'roomnumber': roomnumber, 'workphone': workphone, 'homephone': homephone}) cmd.extend(['-c', gecos_field]) cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L122-L176
[ "def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n", "def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n", "def _build_gecos(gecos_dict):\n '''\n Accepts a dictionary entry containing GECOS field names and their values,\n and returns a full GECOS comment string, to be used with pw usermod.\n '''\n return u'{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''),\n gecos_dict.get('roomnumber', ''),\n gecos_dict.get('workphone', ''),\n gecos_dict.get('homephone', ''))\n" ]
# -*- coding: utf-8 -*- ''' Manage users with the pw command .. important:: If you feel that Salt should be using this module to manage users on a minion, and it is using a different module (or gives an error similar to *'user.info' is not available*), see :ref:`here <module-provider-override>`. ''' # Notes: # ------ # # Format of the master.passwd file: # # - name User's login name. # - password User's encrypted password. # - uid User's id. # - gid User's login group id. # - class User's login class. # - change Password change time. # - expire Account expiration time. # - gecos General information about the user. # - home_dir User's home directory. # - shell User's login shell. # # The usershow command allows viewing of an account in a format that is # identical to the format used in /etc/master.passwd (with the password field # replaced with a ‘*’.) # # Example: # % pw usershow -n someuser # someuser:*:1001:1001::0:0:SomeUser Name:/home/someuser:/bin/sh # Import python libs from __future__ import absolute_import, unicode_literals, print_function import copy import logging try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False # Import 3rd party libs from salt.ext import six # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.user from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'user' def __virtual__(): ''' Set the user module if the kernel is FreeBSD or DragonFly ''' if HAS_PWD and __grains__['kernel'] in ('FreeBSD', 'DragonFly'): return __virtualname__ return (False, 'The pw_user execution module cannot be loaded: the pwd python module is not available or the system is not FreeBSD.') def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' try: gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) except KeyError: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 4: gecos_field.append('') return {'fullname': salt.utils.data.decode(gecos_field[0]), 'roomnumber': salt.utils.data.decode(gecos_field[1]), 'workphone': salt.utils.data.decode(gecos_field[2]), 'homephone': salt.utils.data.decode(gecos_field[3])} def _build_gecos(gecos_dict): ''' Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with pw usermod. ''' return u'{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''), gecos_dict.get('roomnumber', ''), gecos_dict.get('workphone', ''), gecos_dict.get('homephone', '')) def _update_gecos(name, key, value): ''' Common code to change a user's GECOS information ''' if not isinstance(value, six.string_types): value = six.text_type(value) pre_info = _get_gecos(name) if not pre_info: return False if value == pre_info[key]: return True gecos_data = copy.deepcopy(pre_info) gecos_data[key] = value cmd = ['pw', 'usermod', name, '-c', _build_gecos(gecos_data)] __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) return _get_gecos(name).get(key) == value def delete(name, remove=False, force=False): ''' Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' if salt.utils.data.is_true(force): log.error('pw userdel does not support force-deleting user while ' 'user is logged in') cmd = ['pw', 'userdel'] if remove: cmd.append('-r') cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def getent(refresh=False): ''' Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] for data in pwd.getpwall(): ret.append(info(data.pw_name)) __context__['user.getent'] = ret return ret def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if uid == pre_info['uid']: return True cmd = ['pw', 'usermod', '-u', uid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('uid') == uid def chgid(name, gid): ''' Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if gid == pre_info['gid']: return True cmd = ['pw', 'usermod', '-g', gid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('gid') == gid def chshell(name, shell): ''' Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if shell == pre_info['shell']: return True cmd = ['pw', 'usermod', '-s', shell, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('shell') == shell def chhome(name, home, persist=False): ''' Set a new home directory for an existing user name Username to modify home New home directory to set persist : False Set to ``True`` to prevent configuration files in the new home directory from being overwritten by the files from the skeleton directory. CLI Example: .. code-block:: bash salt '*' user.chhome foo /home/users/foo True ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if home == pre_info['home']: return True cmd = ['pw', 'usermod', name, '-d', home] if persist: cmd.append('-m') __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('home') == home def chgroups(name, groups, append=False): ''' Change the groups to which a user belongs name Username to modify groups List of groups to set for the user. Can be passed as a comma-separated list or a Python list. append : False Set to ``True`` to append these groups to the user's existing list of groups. Otherwise, the specified groups will replace any existing groups for the user. CLI Example: .. code-block:: bash salt '*' user.chgroups foo wheel,root True ''' if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if ugrps == set(groups): return True if append: groups += ugrps cmd = ['pw', 'usermod', '-G', ','.join(groups), '-n', name] return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def chfullname(name, fullname): ''' Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo "Foo Bar" ''' return _update_gecos(name, 'fullname', fullname) def chroomnumber(name, roomnumber): ''' Change the user's Room Number CLI Example: .. code-block:: bash salt '*' user.chroomnumber foo 123 ''' return _update_gecos(name, 'roomnumber', roomnumber) def chworkphone(name, workphone): ''' Change the user's Work Phone CLI Example: .. code-block:: bash salt '*' user.chworkphone foo "7735550123" ''' return _update_gecos(name, 'workphone', workphone) def chhomephone(name, homephone): ''' Change the user's Home Phone CLI Example: .. code-block:: bash salt '*' user.chhomephone foo "7735551234" ''' return _update_gecos(name, 'homephone', homephone) def chloginclass(name, loginclass, root=None): ''' Change the default login class of the user .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff ''' if loginclass == get_loginclass(name): return True cmd = ['pw', 'usermod', '-L', '{0}'.format(loginclass), '-n', '{0}'.format(name)] __salt__['cmd.run'](cmd, python_shell=False) return get_loginclass(name) == loginclass def info(name): ''' Return user information CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} try: data = pwd.getpwnam(name) ret['gid'] = data.pw_gid ret['groups'] = list_groups(name) ret['home'] = data.pw_dir ret['name'] = data.pw_name ret['passwd'] = data.pw_passwd ret['shell'] = data.pw_shell ret['uid'] = data.pw_uid # Put GECOS info into a list gecos_field = data.pw_gecos.split(',', 3) # Assign empty strings for any unspecified GECOS fields while len(gecos_field) < 4: gecos_field.append('') ret['fullname'] = gecos_field[0] ret['roomnumber'] = gecos_field[1] ret['workphone'] = gecos_field[2] ret['homephone'] = gecos_field[3] except KeyError: return {} return ret def get_loginclass(name): ''' Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' userinfo = __salt__['cmd.run_stdout'](['pw', 'usershow', '-n', name]) userinfo = userinfo.split(':') return userinfo[4] if len(userinfo) == 10 else '' def list_groups(name): ''' Return a list of groups the named user belongs to CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' return salt.utils.user.get_group_list(name) def list_users(): ''' Return a list of all users CLI Example: .. code-block:: bash salt '*' user.list_users ''' return sorted([user.pw_name for user in pwd.getpwall()]) def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info = info(new_name) if new_info: raise CommandExecutionError( 'User \'{0}\' already exists'.format(new_name) ) cmd = ['pw', 'usermod', '-l', new_name, '-n', name] __salt__['cmd.run'](cmd) post_info = info(new_name) if post_info['name'] != current_info['name']: return post_info['name'] == new_name return False
saltstack/salt
salt/modules/pw_user.py
getent
python
def getent(refresh=False): ''' Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] for data in pwd.getpwall(): ret.append(info(data.pw_name)) __context__['user.getent'] = ret return ret
Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L199-L216
[ "def info(name):\n '''\n Return user information\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' user.info root\n '''\n ret = {}\n try:\n data = pwd.getpwnam(name)\n ret['gid'] = data.pw_gid\n ret['groups'] = list_groups(name)\n ret['home'] = data.pw_dir\n ret['name'] = data.pw_name\n ret['passwd'] = data.pw_passwd\n ret['shell'] = data.pw_shell\n ret['uid'] = data.pw_uid\n # Put GECOS info into a list\n gecos_field = data.pw_gecos.split(',', 3)\n # Assign empty strings for any unspecified GECOS fields\n while len(gecos_field) < 4:\n gecos_field.append('')\n ret['fullname'] = gecos_field[0]\n ret['roomnumber'] = gecos_field[1]\n ret['workphone'] = gecos_field[2]\n ret['homephone'] = gecos_field[3]\n except KeyError:\n return {}\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage users with the pw command .. important:: If you feel that Salt should be using this module to manage users on a minion, and it is using a different module (or gives an error similar to *'user.info' is not available*), see :ref:`here <module-provider-override>`. ''' # Notes: # ------ # # Format of the master.passwd file: # # - name User's login name. # - password User's encrypted password. # - uid User's id. # - gid User's login group id. # - class User's login class. # - change Password change time. # - expire Account expiration time. # - gecos General information about the user. # - home_dir User's home directory. # - shell User's login shell. # # The usershow command allows viewing of an account in a format that is # identical to the format used in /etc/master.passwd (with the password field # replaced with a ‘*’.) # # Example: # % pw usershow -n someuser # someuser:*:1001:1001::0:0:SomeUser Name:/home/someuser:/bin/sh # Import python libs from __future__ import absolute_import, unicode_literals, print_function import copy import logging try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False # Import 3rd party libs from salt.ext import six # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.user from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'user' def __virtual__(): ''' Set the user module if the kernel is FreeBSD or DragonFly ''' if HAS_PWD and __grains__['kernel'] in ('FreeBSD', 'DragonFly'): return __virtualname__ return (False, 'The pw_user execution module cannot be loaded: the pwd python module is not available or the system is not FreeBSD.') def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' try: gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) except KeyError: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 4: gecos_field.append('') return {'fullname': salt.utils.data.decode(gecos_field[0]), 'roomnumber': salt.utils.data.decode(gecos_field[1]), 'workphone': salt.utils.data.decode(gecos_field[2]), 'homephone': salt.utils.data.decode(gecos_field[3])} def _build_gecos(gecos_dict): ''' Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with pw usermod. ''' return u'{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''), gecos_dict.get('roomnumber', ''), gecos_dict.get('workphone', ''), gecos_dict.get('homephone', '')) def _update_gecos(name, key, value): ''' Common code to change a user's GECOS information ''' if not isinstance(value, six.string_types): value = six.text_type(value) pre_info = _get_gecos(name) if not pre_info: return False if value == pre_info[key]: return True gecos_data = copy.deepcopy(pre_info) gecos_data[key] = value cmd = ['pw', 'usermod', name, '-c', _build_gecos(gecos_data)] __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) return _get_gecos(name).get(key) == value def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, fullname='', roomnumber='', workphone='', homephone='', createhome=True, loginclass=None, **kwargs): ''' Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if salt.utils.data.is_true(kwargs.pop('system', False)): log.warning('pw_user module does not support the \'system\' argument') if kwargs: log.warning('Invalid kwargs passed to user.add') if isinstance(groups, six.string_types): groups = groups.split(',') cmd = ['pw', 'useradd'] if uid: cmd.extend(['-u', uid]) if gid: cmd.extend(['-g', gid]) if groups: cmd.extend(['-G', ','.join(groups)]) if home is not None: cmd.extend(['-d', home]) if createhome is True: cmd.append('-m') if loginclass: cmd.extend(['-L', loginclass]) if shell: cmd.extend(['-s', shell]) if not salt.utils.data.is_true(unique): cmd.append('-o') gecos_field = _build_gecos({'fullname': fullname, 'roomnumber': roomnumber, 'workphone': workphone, 'homephone': homephone}) cmd.extend(['-c', gecos_field]) cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def delete(name, remove=False, force=False): ''' Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' if salt.utils.data.is_true(force): log.error('pw userdel does not support force-deleting user while ' 'user is logged in') cmd = ['pw', 'userdel'] if remove: cmd.append('-r') cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if uid == pre_info['uid']: return True cmd = ['pw', 'usermod', '-u', uid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('uid') == uid def chgid(name, gid): ''' Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if gid == pre_info['gid']: return True cmd = ['pw', 'usermod', '-g', gid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('gid') == gid def chshell(name, shell): ''' Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if shell == pre_info['shell']: return True cmd = ['pw', 'usermod', '-s', shell, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('shell') == shell def chhome(name, home, persist=False): ''' Set a new home directory for an existing user name Username to modify home New home directory to set persist : False Set to ``True`` to prevent configuration files in the new home directory from being overwritten by the files from the skeleton directory. CLI Example: .. code-block:: bash salt '*' user.chhome foo /home/users/foo True ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if home == pre_info['home']: return True cmd = ['pw', 'usermod', name, '-d', home] if persist: cmd.append('-m') __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('home') == home def chgroups(name, groups, append=False): ''' Change the groups to which a user belongs name Username to modify groups List of groups to set for the user. Can be passed as a comma-separated list or a Python list. append : False Set to ``True`` to append these groups to the user's existing list of groups. Otherwise, the specified groups will replace any existing groups for the user. CLI Example: .. code-block:: bash salt '*' user.chgroups foo wheel,root True ''' if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if ugrps == set(groups): return True if append: groups += ugrps cmd = ['pw', 'usermod', '-G', ','.join(groups), '-n', name] return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def chfullname(name, fullname): ''' Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo "Foo Bar" ''' return _update_gecos(name, 'fullname', fullname) def chroomnumber(name, roomnumber): ''' Change the user's Room Number CLI Example: .. code-block:: bash salt '*' user.chroomnumber foo 123 ''' return _update_gecos(name, 'roomnumber', roomnumber) def chworkphone(name, workphone): ''' Change the user's Work Phone CLI Example: .. code-block:: bash salt '*' user.chworkphone foo "7735550123" ''' return _update_gecos(name, 'workphone', workphone) def chhomephone(name, homephone): ''' Change the user's Home Phone CLI Example: .. code-block:: bash salt '*' user.chhomephone foo "7735551234" ''' return _update_gecos(name, 'homephone', homephone) def chloginclass(name, loginclass, root=None): ''' Change the default login class of the user .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff ''' if loginclass == get_loginclass(name): return True cmd = ['pw', 'usermod', '-L', '{0}'.format(loginclass), '-n', '{0}'.format(name)] __salt__['cmd.run'](cmd, python_shell=False) return get_loginclass(name) == loginclass def info(name): ''' Return user information CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} try: data = pwd.getpwnam(name) ret['gid'] = data.pw_gid ret['groups'] = list_groups(name) ret['home'] = data.pw_dir ret['name'] = data.pw_name ret['passwd'] = data.pw_passwd ret['shell'] = data.pw_shell ret['uid'] = data.pw_uid # Put GECOS info into a list gecos_field = data.pw_gecos.split(',', 3) # Assign empty strings for any unspecified GECOS fields while len(gecos_field) < 4: gecos_field.append('') ret['fullname'] = gecos_field[0] ret['roomnumber'] = gecos_field[1] ret['workphone'] = gecos_field[2] ret['homephone'] = gecos_field[3] except KeyError: return {} return ret def get_loginclass(name): ''' Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' userinfo = __salt__['cmd.run_stdout'](['pw', 'usershow', '-n', name]) userinfo = userinfo.split(':') return userinfo[4] if len(userinfo) == 10 else '' def list_groups(name): ''' Return a list of groups the named user belongs to CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' return salt.utils.user.get_group_list(name) def list_users(): ''' Return a list of all users CLI Example: .. code-block:: bash salt '*' user.list_users ''' return sorted([user.pw_name for user in pwd.getpwall()]) def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info = info(new_name) if new_info: raise CommandExecutionError( 'User \'{0}\' already exists'.format(new_name) ) cmd = ['pw', 'usermod', '-l', new_name, '-n', name] __salt__['cmd.run'](cmd) post_info = info(new_name) if post_info['name'] != current_info['name']: return post_info['name'] == new_name return False
saltstack/salt
salt/modules/pw_user.py
chuid
python
def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if uid == pre_info['uid']: return True cmd = ['pw', 'usermod', '-u', uid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('uid') == uid
Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L219-L238
[ "def info(name):\n '''\n Return user information\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' user.info root\n '''\n ret = {}\n try:\n data = pwd.getpwnam(name)\n ret['gid'] = data.pw_gid\n ret['groups'] = list_groups(name)\n ret['home'] = data.pw_dir\n ret['name'] = data.pw_name\n ret['passwd'] = data.pw_passwd\n ret['shell'] = data.pw_shell\n ret['uid'] = data.pw_uid\n # Put GECOS info into a list\n gecos_field = data.pw_gecos.split(',', 3)\n # Assign empty strings for any unspecified GECOS fields\n while len(gecos_field) < 4:\n gecos_field.append('')\n ret['fullname'] = gecos_field[0]\n ret['roomnumber'] = gecos_field[1]\n ret['workphone'] = gecos_field[2]\n ret['homephone'] = gecos_field[3]\n except KeyError:\n return {}\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage users with the pw command .. important:: If you feel that Salt should be using this module to manage users on a minion, and it is using a different module (or gives an error similar to *'user.info' is not available*), see :ref:`here <module-provider-override>`. ''' # Notes: # ------ # # Format of the master.passwd file: # # - name User's login name. # - password User's encrypted password. # - uid User's id. # - gid User's login group id. # - class User's login class. # - change Password change time. # - expire Account expiration time. # - gecos General information about the user. # - home_dir User's home directory. # - shell User's login shell. # # The usershow command allows viewing of an account in a format that is # identical to the format used in /etc/master.passwd (with the password field # replaced with a ‘*’.) # # Example: # % pw usershow -n someuser # someuser:*:1001:1001::0:0:SomeUser Name:/home/someuser:/bin/sh # Import python libs from __future__ import absolute_import, unicode_literals, print_function import copy import logging try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False # Import 3rd party libs from salt.ext import six # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.user from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'user' def __virtual__(): ''' Set the user module if the kernel is FreeBSD or DragonFly ''' if HAS_PWD and __grains__['kernel'] in ('FreeBSD', 'DragonFly'): return __virtualname__ return (False, 'The pw_user execution module cannot be loaded: the pwd python module is not available or the system is not FreeBSD.') def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' try: gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) except KeyError: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 4: gecos_field.append('') return {'fullname': salt.utils.data.decode(gecos_field[0]), 'roomnumber': salt.utils.data.decode(gecos_field[1]), 'workphone': salt.utils.data.decode(gecos_field[2]), 'homephone': salt.utils.data.decode(gecos_field[3])} def _build_gecos(gecos_dict): ''' Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with pw usermod. ''' return u'{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''), gecos_dict.get('roomnumber', ''), gecos_dict.get('workphone', ''), gecos_dict.get('homephone', '')) def _update_gecos(name, key, value): ''' Common code to change a user's GECOS information ''' if not isinstance(value, six.string_types): value = six.text_type(value) pre_info = _get_gecos(name) if not pre_info: return False if value == pre_info[key]: return True gecos_data = copy.deepcopy(pre_info) gecos_data[key] = value cmd = ['pw', 'usermod', name, '-c', _build_gecos(gecos_data)] __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) return _get_gecos(name).get(key) == value def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, fullname='', roomnumber='', workphone='', homephone='', createhome=True, loginclass=None, **kwargs): ''' Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if salt.utils.data.is_true(kwargs.pop('system', False)): log.warning('pw_user module does not support the \'system\' argument') if kwargs: log.warning('Invalid kwargs passed to user.add') if isinstance(groups, six.string_types): groups = groups.split(',') cmd = ['pw', 'useradd'] if uid: cmd.extend(['-u', uid]) if gid: cmd.extend(['-g', gid]) if groups: cmd.extend(['-G', ','.join(groups)]) if home is not None: cmd.extend(['-d', home]) if createhome is True: cmd.append('-m') if loginclass: cmd.extend(['-L', loginclass]) if shell: cmd.extend(['-s', shell]) if not salt.utils.data.is_true(unique): cmd.append('-o') gecos_field = _build_gecos({'fullname': fullname, 'roomnumber': roomnumber, 'workphone': workphone, 'homephone': homephone}) cmd.extend(['-c', gecos_field]) cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def delete(name, remove=False, force=False): ''' Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' if salt.utils.data.is_true(force): log.error('pw userdel does not support force-deleting user while ' 'user is logged in') cmd = ['pw', 'userdel'] if remove: cmd.append('-r') cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def getent(refresh=False): ''' Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] for data in pwd.getpwall(): ret.append(info(data.pw_name)) __context__['user.getent'] = ret return ret def chgid(name, gid): ''' Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if gid == pre_info['gid']: return True cmd = ['pw', 'usermod', '-g', gid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('gid') == gid def chshell(name, shell): ''' Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if shell == pre_info['shell']: return True cmd = ['pw', 'usermod', '-s', shell, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('shell') == shell def chhome(name, home, persist=False): ''' Set a new home directory for an existing user name Username to modify home New home directory to set persist : False Set to ``True`` to prevent configuration files in the new home directory from being overwritten by the files from the skeleton directory. CLI Example: .. code-block:: bash salt '*' user.chhome foo /home/users/foo True ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if home == pre_info['home']: return True cmd = ['pw', 'usermod', name, '-d', home] if persist: cmd.append('-m') __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('home') == home def chgroups(name, groups, append=False): ''' Change the groups to which a user belongs name Username to modify groups List of groups to set for the user. Can be passed as a comma-separated list or a Python list. append : False Set to ``True`` to append these groups to the user's existing list of groups. Otherwise, the specified groups will replace any existing groups for the user. CLI Example: .. code-block:: bash salt '*' user.chgroups foo wheel,root True ''' if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if ugrps == set(groups): return True if append: groups += ugrps cmd = ['pw', 'usermod', '-G', ','.join(groups), '-n', name] return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def chfullname(name, fullname): ''' Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo "Foo Bar" ''' return _update_gecos(name, 'fullname', fullname) def chroomnumber(name, roomnumber): ''' Change the user's Room Number CLI Example: .. code-block:: bash salt '*' user.chroomnumber foo 123 ''' return _update_gecos(name, 'roomnumber', roomnumber) def chworkphone(name, workphone): ''' Change the user's Work Phone CLI Example: .. code-block:: bash salt '*' user.chworkphone foo "7735550123" ''' return _update_gecos(name, 'workphone', workphone) def chhomephone(name, homephone): ''' Change the user's Home Phone CLI Example: .. code-block:: bash salt '*' user.chhomephone foo "7735551234" ''' return _update_gecos(name, 'homephone', homephone) def chloginclass(name, loginclass, root=None): ''' Change the default login class of the user .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff ''' if loginclass == get_loginclass(name): return True cmd = ['pw', 'usermod', '-L', '{0}'.format(loginclass), '-n', '{0}'.format(name)] __salt__['cmd.run'](cmd, python_shell=False) return get_loginclass(name) == loginclass def info(name): ''' Return user information CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} try: data = pwd.getpwnam(name) ret['gid'] = data.pw_gid ret['groups'] = list_groups(name) ret['home'] = data.pw_dir ret['name'] = data.pw_name ret['passwd'] = data.pw_passwd ret['shell'] = data.pw_shell ret['uid'] = data.pw_uid # Put GECOS info into a list gecos_field = data.pw_gecos.split(',', 3) # Assign empty strings for any unspecified GECOS fields while len(gecos_field) < 4: gecos_field.append('') ret['fullname'] = gecos_field[0] ret['roomnumber'] = gecos_field[1] ret['workphone'] = gecos_field[2] ret['homephone'] = gecos_field[3] except KeyError: return {} return ret def get_loginclass(name): ''' Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' userinfo = __salt__['cmd.run_stdout'](['pw', 'usershow', '-n', name]) userinfo = userinfo.split(':') return userinfo[4] if len(userinfo) == 10 else '' def list_groups(name): ''' Return a list of groups the named user belongs to CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' return salt.utils.user.get_group_list(name) def list_users(): ''' Return a list of all users CLI Example: .. code-block:: bash salt '*' user.list_users ''' return sorted([user.pw_name for user in pwd.getpwall()]) def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info = info(new_name) if new_info: raise CommandExecutionError( 'User \'{0}\' already exists'.format(new_name) ) cmd = ['pw', 'usermod', '-l', new_name, '-n', name] __salt__['cmd.run'](cmd) post_info = info(new_name) if post_info['name'] != current_info['name']: return post_info['name'] == new_name return False
saltstack/salt
salt/modules/pw_user.py
chloginclass
python
def chloginclass(name, loginclass, root=None): ''' Change the default login class of the user .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff ''' if loginclass == get_loginclass(name): return True cmd = ['pw', 'usermod', '-L', '{0}'.format(loginclass), '-n', '{0}'.format(name)] __salt__['cmd.run'](cmd, python_shell=False) return get_loginclass(name) == loginclass
Change the default login class of the user .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L405-L425
[ "def get_loginclass(name):\n '''\n Get the login class of the user\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' user.get_loginclass foo\n\n '''\n\n userinfo = __salt__['cmd.run_stdout'](['pw', 'usershow', '-n', name])\n userinfo = userinfo.split(':')\n\n return userinfo[4] if len(userinfo) == 10 else ''\n" ]
# -*- coding: utf-8 -*- ''' Manage users with the pw command .. important:: If you feel that Salt should be using this module to manage users on a minion, and it is using a different module (or gives an error similar to *'user.info' is not available*), see :ref:`here <module-provider-override>`. ''' # Notes: # ------ # # Format of the master.passwd file: # # - name User's login name. # - password User's encrypted password. # - uid User's id. # - gid User's login group id. # - class User's login class. # - change Password change time. # - expire Account expiration time. # - gecos General information about the user. # - home_dir User's home directory. # - shell User's login shell. # # The usershow command allows viewing of an account in a format that is # identical to the format used in /etc/master.passwd (with the password field # replaced with a ‘*’.) # # Example: # % pw usershow -n someuser # someuser:*:1001:1001::0:0:SomeUser Name:/home/someuser:/bin/sh # Import python libs from __future__ import absolute_import, unicode_literals, print_function import copy import logging try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False # Import 3rd party libs from salt.ext import six # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.user from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'user' def __virtual__(): ''' Set the user module if the kernel is FreeBSD or DragonFly ''' if HAS_PWD and __grains__['kernel'] in ('FreeBSD', 'DragonFly'): return __virtualname__ return (False, 'The pw_user execution module cannot be loaded: the pwd python module is not available or the system is not FreeBSD.') def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' try: gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) except KeyError: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 4: gecos_field.append('') return {'fullname': salt.utils.data.decode(gecos_field[0]), 'roomnumber': salt.utils.data.decode(gecos_field[1]), 'workphone': salt.utils.data.decode(gecos_field[2]), 'homephone': salt.utils.data.decode(gecos_field[3])} def _build_gecos(gecos_dict): ''' Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with pw usermod. ''' return u'{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''), gecos_dict.get('roomnumber', ''), gecos_dict.get('workphone', ''), gecos_dict.get('homephone', '')) def _update_gecos(name, key, value): ''' Common code to change a user's GECOS information ''' if not isinstance(value, six.string_types): value = six.text_type(value) pre_info = _get_gecos(name) if not pre_info: return False if value == pre_info[key]: return True gecos_data = copy.deepcopy(pre_info) gecos_data[key] = value cmd = ['pw', 'usermod', name, '-c', _build_gecos(gecos_data)] __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) return _get_gecos(name).get(key) == value def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, fullname='', roomnumber='', workphone='', homephone='', createhome=True, loginclass=None, **kwargs): ''' Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if salt.utils.data.is_true(kwargs.pop('system', False)): log.warning('pw_user module does not support the \'system\' argument') if kwargs: log.warning('Invalid kwargs passed to user.add') if isinstance(groups, six.string_types): groups = groups.split(',') cmd = ['pw', 'useradd'] if uid: cmd.extend(['-u', uid]) if gid: cmd.extend(['-g', gid]) if groups: cmd.extend(['-G', ','.join(groups)]) if home is not None: cmd.extend(['-d', home]) if createhome is True: cmd.append('-m') if loginclass: cmd.extend(['-L', loginclass]) if shell: cmd.extend(['-s', shell]) if not salt.utils.data.is_true(unique): cmd.append('-o') gecos_field = _build_gecos({'fullname': fullname, 'roomnumber': roomnumber, 'workphone': workphone, 'homephone': homephone}) cmd.extend(['-c', gecos_field]) cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def delete(name, remove=False, force=False): ''' Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' if salt.utils.data.is_true(force): log.error('pw userdel does not support force-deleting user while ' 'user is logged in') cmd = ['pw', 'userdel'] if remove: cmd.append('-r') cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def getent(refresh=False): ''' Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] for data in pwd.getpwall(): ret.append(info(data.pw_name)) __context__['user.getent'] = ret return ret def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if uid == pre_info['uid']: return True cmd = ['pw', 'usermod', '-u', uid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('uid') == uid def chgid(name, gid): ''' Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if gid == pre_info['gid']: return True cmd = ['pw', 'usermod', '-g', gid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('gid') == gid def chshell(name, shell): ''' Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if shell == pre_info['shell']: return True cmd = ['pw', 'usermod', '-s', shell, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('shell') == shell def chhome(name, home, persist=False): ''' Set a new home directory for an existing user name Username to modify home New home directory to set persist : False Set to ``True`` to prevent configuration files in the new home directory from being overwritten by the files from the skeleton directory. CLI Example: .. code-block:: bash salt '*' user.chhome foo /home/users/foo True ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if home == pre_info['home']: return True cmd = ['pw', 'usermod', name, '-d', home] if persist: cmd.append('-m') __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('home') == home def chgroups(name, groups, append=False): ''' Change the groups to which a user belongs name Username to modify groups List of groups to set for the user. Can be passed as a comma-separated list or a Python list. append : False Set to ``True`` to append these groups to the user's existing list of groups. Otherwise, the specified groups will replace any existing groups for the user. CLI Example: .. code-block:: bash salt '*' user.chgroups foo wheel,root True ''' if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if ugrps == set(groups): return True if append: groups += ugrps cmd = ['pw', 'usermod', '-G', ','.join(groups), '-n', name] return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def chfullname(name, fullname): ''' Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo "Foo Bar" ''' return _update_gecos(name, 'fullname', fullname) def chroomnumber(name, roomnumber): ''' Change the user's Room Number CLI Example: .. code-block:: bash salt '*' user.chroomnumber foo 123 ''' return _update_gecos(name, 'roomnumber', roomnumber) def chworkphone(name, workphone): ''' Change the user's Work Phone CLI Example: .. code-block:: bash salt '*' user.chworkphone foo "7735550123" ''' return _update_gecos(name, 'workphone', workphone) def chhomephone(name, homephone): ''' Change the user's Home Phone CLI Example: .. code-block:: bash salt '*' user.chhomephone foo "7735551234" ''' return _update_gecos(name, 'homephone', homephone) def info(name): ''' Return user information CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} try: data = pwd.getpwnam(name) ret['gid'] = data.pw_gid ret['groups'] = list_groups(name) ret['home'] = data.pw_dir ret['name'] = data.pw_name ret['passwd'] = data.pw_passwd ret['shell'] = data.pw_shell ret['uid'] = data.pw_uid # Put GECOS info into a list gecos_field = data.pw_gecos.split(',', 3) # Assign empty strings for any unspecified GECOS fields while len(gecos_field) < 4: gecos_field.append('') ret['fullname'] = gecos_field[0] ret['roomnumber'] = gecos_field[1] ret['workphone'] = gecos_field[2] ret['homephone'] = gecos_field[3] except KeyError: return {} return ret def get_loginclass(name): ''' Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' userinfo = __salt__['cmd.run_stdout'](['pw', 'usershow', '-n', name]) userinfo = userinfo.split(':') return userinfo[4] if len(userinfo) == 10 else '' def list_groups(name): ''' Return a list of groups the named user belongs to CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' return salt.utils.user.get_group_list(name) def list_users(): ''' Return a list of all users CLI Example: .. code-block:: bash salt '*' user.list_users ''' return sorted([user.pw_name for user in pwd.getpwall()]) def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info = info(new_name) if new_info: raise CommandExecutionError( 'User \'{0}\' already exists'.format(new_name) ) cmd = ['pw', 'usermod', '-l', new_name, '-n', name] __salt__['cmd.run'](cmd) post_info = info(new_name) if post_info['name'] != current_info['name']: return post_info['name'] == new_name return False
saltstack/salt
salt/modules/pw_user.py
info
python
def info(name): ''' Return user information CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} try: data = pwd.getpwnam(name) ret['gid'] = data.pw_gid ret['groups'] = list_groups(name) ret['home'] = data.pw_dir ret['name'] = data.pw_name ret['passwd'] = data.pw_passwd ret['shell'] = data.pw_shell ret['uid'] = data.pw_uid # Put GECOS info into a list gecos_field = data.pw_gecos.split(',', 3) # Assign empty strings for any unspecified GECOS fields while len(gecos_field) < 4: gecos_field.append('') ret['fullname'] = gecos_field[0] ret['roomnumber'] = gecos_field[1] ret['workphone'] = gecos_field[2] ret['homephone'] = gecos_field[3] except KeyError: return {} return ret
Return user information CLI Example: .. code-block:: bash salt '*' user.info root
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L428-L459
[ "def list_groups(name):\n '''\n Return a list of groups the named user belongs to\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' user.list_groups foo\n '''\n return salt.utils.user.get_group_list(name)\n" ]
# -*- coding: utf-8 -*- ''' Manage users with the pw command .. important:: If you feel that Salt should be using this module to manage users on a minion, and it is using a different module (or gives an error similar to *'user.info' is not available*), see :ref:`here <module-provider-override>`. ''' # Notes: # ------ # # Format of the master.passwd file: # # - name User's login name. # - password User's encrypted password. # - uid User's id. # - gid User's login group id. # - class User's login class. # - change Password change time. # - expire Account expiration time. # - gecos General information about the user. # - home_dir User's home directory. # - shell User's login shell. # # The usershow command allows viewing of an account in a format that is # identical to the format used in /etc/master.passwd (with the password field # replaced with a ‘*’.) # # Example: # % pw usershow -n someuser # someuser:*:1001:1001::0:0:SomeUser Name:/home/someuser:/bin/sh # Import python libs from __future__ import absolute_import, unicode_literals, print_function import copy import logging try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False # Import 3rd party libs from salt.ext import six # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.user from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'user' def __virtual__(): ''' Set the user module if the kernel is FreeBSD or DragonFly ''' if HAS_PWD and __grains__['kernel'] in ('FreeBSD', 'DragonFly'): return __virtualname__ return (False, 'The pw_user execution module cannot be loaded: the pwd python module is not available or the system is not FreeBSD.') def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' try: gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) except KeyError: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 4: gecos_field.append('') return {'fullname': salt.utils.data.decode(gecos_field[0]), 'roomnumber': salt.utils.data.decode(gecos_field[1]), 'workphone': salt.utils.data.decode(gecos_field[2]), 'homephone': salt.utils.data.decode(gecos_field[3])} def _build_gecos(gecos_dict): ''' Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with pw usermod. ''' return u'{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''), gecos_dict.get('roomnumber', ''), gecos_dict.get('workphone', ''), gecos_dict.get('homephone', '')) def _update_gecos(name, key, value): ''' Common code to change a user's GECOS information ''' if not isinstance(value, six.string_types): value = six.text_type(value) pre_info = _get_gecos(name) if not pre_info: return False if value == pre_info[key]: return True gecos_data = copy.deepcopy(pre_info) gecos_data[key] = value cmd = ['pw', 'usermod', name, '-c', _build_gecos(gecos_data)] __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) return _get_gecos(name).get(key) == value def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, fullname='', roomnumber='', workphone='', homephone='', createhome=True, loginclass=None, **kwargs): ''' Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if salt.utils.data.is_true(kwargs.pop('system', False)): log.warning('pw_user module does not support the \'system\' argument') if kwargs: log.warning('Invalid kwargs passed to user.add') if isinstance(groups, six.string_types): groups = groups.split(',') cmd = ['pw', 'useradd'] if uid: cmd.extend(['-u', uid]) if gid: cmd.extend(['-g', gid]) if groups: cmd.extend(['-G', ','.join(groups)]) if home is not None: cmd.extend(['-d', home]) if createhome is True: cmd.append('-m') if loginclass: cmd.extend(['-L', loginclass]) if shell: cmd.extend(['-s', shell]) if not salt.utils.data.is_true(unique): cmd.append('-o') gecos_field = _build_gecos({'fullname': fullname, 'roomnumber': roomnumber, 'workphone': workphone, 'homephone': homephone}) cmd.extend(['-c', gecos_field]) cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def delete(name, remove=False, force=False): ''' Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' if salt.utils.data.is_true(force): log.error('pw userdel does not support force-deleting user while ' 'user is logged in') cmd = ['pw', 'userdel'] if remove: cmd.append('-r') cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def getent(refresh=False): ''' Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] for data in pwd.getpwall(): ret.append(info(data.pw_name)) __context__['user.getent'] = ret return ret def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if uid == pre_info['uid']: return True cmd = ['pw', 'usermod', '-u', uid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('uid') == uid def chgid(name, gid): ''' Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if gid == pre_info['gid']: return True cmd = ['pw', 'usermod', '-g', gid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('gid') == gid def chshell(name, shell): ''' Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if shell == pre_info['shell']: return True cmd = ['pw', 'usermod', '-s', shell, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('shell') == shell def chhome(name, home, persist=False): ''' Set a new home directory for an existing user name Username to modify home New home directory to set persist : False Set to ``True`` to prevent configuration files in the new home directory from being overwritten by the files from the skeleton directory. CLI Example: .. code-block:: bash salt '*' user.chhome foo /home/users/foo True ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if home == pre_info['home']: return True cmd = ['pw', 'usermod', name, '-d', home] if persist: cmd.append('-m') __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('home') == home def chgroups(name, groups, append=False): ''' Change the groups to which a user belongs name Username to modify groups List of groups to set for the user. Can be passed as a comma-separated list or a Python list. append : False Set to ``True`` to append these groups to the user's existing list of groups. Otherwise, the specified groups will replace any existing groups for the user. CLI Example: .. code-block:: bash salt '*' user.chgroups foo wheel,root True ''' if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if ugrps == set(groups): return True if append: groups += ugrps cmd = ['pw', 'usermod', '-G', ','.join(groups), '-n', name] return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def chfullname(name, fullname): ''' Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo "Foo Bar" ''' return _update_gecos(name, 'fullname', fullname) def chroomnumber(name, roomnumber): ''' Change the user's Room Number CLI Example: .. code-block:: bash salt '*' user.chroomnumber foo 123 ''' return _update_gecos(name, 'roomnumber', roomnumber) def chworkphone(name, workphone): ''' Change the user's Work Phone CLI Example: .. code-block:: bash salt '*' user.chworkphone foo "7735550123" ''' return _update_gecos(name, 'workphone', workphone) def chhomephone(name, homephone): ''' Change the user's Home Phone CLI Example: .. code-block:: bash salt '*' user.chhomephone foo "7735551234" ''' return _update_gecos(name, 'homephone', homephone) def chloginclass(name, loginclass, root=None): ''' Change the default login class of the user .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff ''' if loginclass == get_loginclass(name): return True cmd = ['pw', 'usermod', '-L', '{0}'.format(loginclass), '-n', '{0}'.format(name)] __salt__['cmd.run'](cmd, python_shell=False) return get_loginclass(name) == loginclass def get_loginclass(name): ''' Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' userinfo = __salt__['cmd.run_stdout'](['pw', 'usershow', '-n', name]) userinfo = userinfo.split(':') return userinfo[4] if len(userinfo) == 10 else '' def list_groups(name): ''' Return a list of groups the named user belongs to CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' return salt.utils.user.get_group_list(name) def list_users(): ''' Return a list of all users CLI Example: .. code-block:: bash salt '*' user.list_users ''' return sorted([user.pw_name for user in pwd.getpwall()]) def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info = info(new_name) if new_info: raise CommandExecutionError( 'User \'{0}\' already exists'.format(new_name) ) cmd = ['pw', 'usermod', '-l', new_name, '-n', name] __salt__['cmd.run'](cmd) post_info = info(new_name) if post_info['name'] != current_info['name']: return post_info['name'] == new_name return False
saltstack/salt
salt/modules/pw_user.py
get_loginclass
python
def get_loginclass(name): ''' Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' userinfo = __salt__['cmd.run_stdout'](['pw', 'usershow', '-n', name]) userinfo = userinfo.split(':') return userinfo[4] if len(userinfo) == 10 else ''
Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L462-L479
null
# -*- coding: utf-8 -*- ''' Manage users with the pw command .. important:: If you feel that Salt should be using this module to manage users on a minion, and it is using a different module (or gives an error similar to *'user.info' is not available*), see :ref:`here <module-provider-override>`. ''' # Notes: # ------ # # Format of the master.passwd file: # # - name User's login name. # - password User's encrypted password. # - uid User's id. # - gid User's login group id. # - class User's login class. # - change Password change time. # - expire Account expiration time. # - gecos General information about the user. # - home_dir User's home directory. # - shell User's login shell. # # The usershow command allows viewing of an account in a format that is # identical to the format used in /etc/master.passwd (with the password field # replaced with a ‘*’.) # # Example: # % pw usershow -n someuser # someuser:*:1001:1001::0:0:SomeUser Name:/home/someuser:/bin/sh # Import python libs from __future__ import absolute_import, unicode_literals, print_function import copy import logging try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False # Import 3rd party libs from salt.ext import six # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.user from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'user' def __virtual__(): ''' Set the user module if the kernel is FreeBSD or DragonFly ''' if HAS_PWD and __grains__['kernel'] in ('FreeBSD', 'DragonFly'): return __virtualname__ return (False, 'The pw_user execution module cannot be loaded: the pwd python module is not available or the system is not FreeBSD.') def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' try: gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) except KeyError: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 4: gecos_field.append('') return {'fullname': salt.utils.data.decode(gecos_field[0]), 'roomnumber': salt.utils.data.decode(gecos_field[1]), 'workphone': salt.utils.data.decode(gecos_field[2]), 'homephone': salt.utils.data.decode(gecos_field[3])} def _build_gecos(gecos_dict): ''' Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with pw usermod. ''' return u'{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''), gecos_dict.get('roomnumber', ''), gecos_dict.get('workphone', ''), gecos_dict.get('homephone', '')) def _update_gecos(name, key, value): ''' Common code to change a user's GECOS information ''' if not isinstance(value, six.string_types): value = six.text_type(value) pre_info = _get_gecos(name) if not pre_info: return False if value == pre_info[key]: return True gecos_data = copy.deepcopy(pre_info) gecos_data[key] = value cmd = ['pw', 'usermod', name, '-c', _build_gecos(gecos_data)] __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) return _get_gecos(name).get(key) == value def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, fullname='', roomnumber='', workphone='', homephone='', createhome=True, loginclass=None, **kwargs): ''' Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if salt.utils.data.is_true(kwargs.pop('system', False)): log.warning('pw_user module does not support the \'system\' argument') if kwargs: log.warning('Invalid kwargs passed to user.add') if isinstance(groups, six.string_types): groups = groups.split(',') cmd = ['pw', 'useradd'] if uid: cmd.extend(['-u', uid]) if gid: cmd.extend(['-g', gid]) if groups: cmd.extend(['-G', ','.join(groups)]) if home is not None: cmd.extend(['-d', home]) if createhome is True: cmd.append('-m') if loginclass: cmd.extend(['-L', loginclass]) if shell: cmd.extend(['-s', shell]) if not salt.utils.data.is_true(unique): cmd.append('-o') gecos_field = _build_gecos({'fullname': fullname, 'roomnumber': roomnumber, 'workphone': workphone, 'homephone': homephone}) cmd.extend(['-c', gecos_field]) cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def delete(name, remove=False, force=False): ''' Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' if salt.utils.data.is_true(force): log.error('pw userdel does not support force-deleting user while ' 'user is logged in') cmd = ['pw', 'userdel'] if remove: cmd.append('-r') cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def getent(refresh=False): ''' Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] for data in pwd.getpwall(): ret.append(info(data.pw_name)) __context__['user.getent'] = ret return ret def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if uid == pre_info['uid']: return True cmd = ['pw', 'usermod', '-u', uid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('uid') == uid def chgid(name, gid): ''' Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if gid == pre_info['gid']: return True cmd = ['pw', 'usermod', '-g', gid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('gid') == gid def chshell(name, shell): ''' Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if shell == pre_info['shell']: return True cmd = ['pw', 'usermod', '-s', shell, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('shell') == shell def chhome(name, home, persist=False): ''' Set a new home directory for an existing user name Username to modify home New home directory to set persist : False Set to ``True`` to prevent configuration files in the new home directory from being overwritten by the files from the skeleton directory. CLI Example: .. code-block:: bash salt '*' user.chhome foo /home/users/foo True ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if home == pre_info['home']: return True cmd = ['pw', 'usermod', name, '-d', home] if persist: cmd.append('-m') __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('home') == home def chgroups(name, groups, append=False): ''' Change the groups to which a user belongs name Username to modify groups List of groups to set for the user. Can be passed as a comma-separated list or a Python list. append : False Set to ``True`` to append these groups to the user's existing list of groups. Otherwise, the specified groups will replace any existing groups for the user. CLI Example: .. code-block:: bash salt '*' user.chgroups foo wheel,root True ''' if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if ugrps == set(groups): return True if append: groups += ugrps cmd = ['pw', 'usermod', '-G', ','.join(groups), '-n', name] return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def chfullname(name, fullname): ''' Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo "Foo Bar" ''' return _update_gecos(name, 'fullname', fullname) def chroomnumber(name, roomnumber): ''' Change the user's Room Number CLI Example: .. code-block:: bash salt '*' user.chroomnumber foo 123 ''' return _update_gecos(name, 'roomnumber', roomnumber) def chworkphone(name, workphone): ''' Change the user's Work Phone CLI Example: .. code-block:: bash salt '*' user.chworkphone foo "7735550123" ''' return _update_gecos(name, 'workphone', workphone) def chhomephone(name, homephone): ''' Change the user's Home Phone CLI Example: .. code-block:: bash salt '*' user.chhomephone foo "7735551234" ''' return _update_gecos(name, 'homephone', homephone) def chloginclass(name, loginclass, root=None): ''' Change the default login class of the user .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff ''' if loginclass == get_loginclass(name): return True cmd = ['pw', 'usermod', '-L', '{0}'.format(loginclass), '-n', '{0}'.format(name)] __salt__['cmd.run'](cmd, python_shell=False) return get_loginclass(name) == loginclass def info(name): ''' Return user information CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} try: data = pwd.getpwnam(name) ret['gid'] = data.pw_gid ret['groups'] = list_groups(name) ret['home'] = data.pw_dir ret['name'] = data.pw_name ret['passwd'] = data.pw_passwd ret['shell'] = data.pw_shell ret['uid'] = data.pw_uid # Put GECOS info into a list gecos_field = data.pw_gecos.split(',', 3) # Assign empty strings for any unspecified GECOS fields while len(gecos_field) < 4: gecos_field.append('') ret['fullname'] = gecos_field[0] ret['roomnumber'] = gecos_field[1] ret['workphone'] = gecos_field[2] ret['homephone'] = gecos_field[3] except KeyError: return {} return ret def list_groups(name): ''' Return a list of groups the named user belongs to CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' return salt.utils.user.get_group_list(name) def list_users(): ''' Return a list of all users CLI Example: .. code-block:: bash salt '*' user.list_users ''' return sorted([user.pw_name for user in pwd.getpwall()]) def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info = info(new_name) if new_info: raise CommandExecutionError( 'User \'{0}\' already exists'.format(new_name) ) cmd = ['pw', 'usermod', '-l', new_name, '-n', name] __salt__['cmd.run'](cmd) post_info = info(new_name) if post_info['name'] != current_info['name']: return post_info['name'] == new_name return False
saltstack/salt
salt/modules/pw_user.py
rename
python
def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info = info(new_name) if new_info: raise CommandExecutionError( 'User \'{0}\' already exists'.format(new_name) ) cmd = ['pw', 'usermod', '-l', new_name, '-n', name] __salt__['cmd.run'](cmd) post_info = info(new_name) if post_info['name'] != current_info['name']: return post_info['name'] == new_name return False
Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L508-L531
[ "def info(name):\n '''\n Return user information\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' user.info root\n '''\n ret = {}\n try:\n data = pwd.getpwnam(name)\n ret['gid'] = data.pw_gid\n ret['groups'] = list_groups(name)\n ret['home'] = data.pw_dir\n ret['name'] = data.pw_name\n ret['passwd'] = data.pw_passwd\n ret['shell'] = data.pw_shell\n ret['uid'] = data.pw_uid\n # Put GECOS info into a list\n gecos_field = data.pw_gecos.split(',', 3)\n # Assign empty strings for any unspecified GECOS fields\n while len(gecos_field) < 4:\n gecos_field.append('')\n ret['fullname'] = gecos_field[0]\n ret['roomnumber'] = gecos_field[1]\n ret['workphone'] = gecos_field[2]\n ret['homephone'] = gecos_field[3]\n except KeyError:\n return {}\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage users with the pw command .. important:: If you feel that Salt should be using this module to manage users on a minion, and it is using a different module (or gives an error similar to *'user.info' is not available*), see :ref:`here <module-provider-override>`. ''' # Notes: # ------ # # Format of the master.passwd file: # # - name User's login name. # - password User's encrypted password. # - uid User's id. # - gid User's login group id. # - class User's login class. # - change Password change time. # - expire Account expiration time. # - gecos General information about the user. # - home_dir User's home directory. # - shell User's login shell. # # The usershow command allows viewing of an account in a format that is # identical to the format used in /etc/master.passwd (with the password field # replaced with a ‘*’.) # # Example: # % pw usershow -n someuser # someuser:*:1001:1001::0:0:SomeUser Name:/home/someuser:/bin/sh # Import python libs from __future__ import absolute_import, unicode_literals, print_function import copy import logging try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False # Import 3rd party libs from salt.ext import six # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.user from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'user' def __virtual__(): ''' Set the user module if the kernel is FreeBSD or DragonFly ''' if HAS_PWD and __grains__['kernel'] in ('FreeBSD', 'DragonFly'): return __virtualname__ return (False, 'The pw_user execution module cannot be loaded: the pwd python module is not available or the system is not FreeBSD.') def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' try: gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) except KeyError: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 4: gecos_field.append('') return {'fullname': salt.utils.data.decode(gecos_field[0]), 'roomnumber': salt.utils.data.decode(gecos_field[1]), 'workphone': salt.utils.data.decode(gecos_field[2]), 'homephone': salt.utils.data.decode(gecos_field[3])} def _build_gecos(gecos_dict): ''' Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with pw usermod. ''' return u'{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''), gecos_dict.get('roomnumber', ''), gecos_dict.get('workphone', ''), gecos_dict.get('homephone', '')) def _update_gecos(name, key, value): ''' Common code to change a user's GECOS information ''' if not isinstance(value, six.string_types): value = six.text_type(value) pre_info = _get_gecos(name) if not pre_info: return False if value == pre_info[key]: return True gecos_data = copy.deepcopy(pre_info) gecos_data[key] = value cmd = ['pw', 'usermod', name, '-c', _build_gecos(gecos_data)] __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) return _get_gecos(name).get(key) == value def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, fullname='', roomnumber='', workphone='', homephone='', createhome=True, loginclass=None, **kwargs): ''' Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if salt.utils.data.is_true(kwargs.pop('system', False)): log.warning('pw_user module does not support the \'system\' argument') if kwargs: log.warning('Invalid kwargs passed to user.add') if isinstance(groups, six.string_types): groups = groups.split(',') cmd = ['pw', 'useradd'] if uid: cmd.extend(['-u', uid]) if gid: cmd.extend(['-g', gid]) if groups: cmd.extend(['-G', ','.join(groups)]) if home is not None: cmd.extend(['-d', home]) if createhome is True: cmd.append('-m') if loginclass: cmd.extend(['-L', loginclass]) if shell: cmd.extend(['-s', shell]) if not salt.utils.data.is_true(unique): cmd.append('-o') gecos_field = _build_gecos({'fullname': fullname, 'roomnumber': roomnumber, 'workphone': workphone, 'homephone': homephone}) cmd.extend(['-c', gecos_field]) cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def delete(name, remove=False, force=False): ''' Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' if salt.utils.data.is_true(force): log.error('pw userdel does not support force-deleting user while ' 'user is logged in') cmd = ['pw', 'userdel'] if remove: cmd.append('-r') cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def getent(refresh=False): ''' Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] for data in pwd.getpwall(): ret.append(info(data.pw_name)) __context__['user.getent'] = ret return ret def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if uid == pre_info['uid']: return True cmd = ['pw', 'usermod', '-u', uid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('uid') == uid def chgid(name, gid): ''' Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if gid == pre_info['gid']: return True cmd = ['pw', 'usermod', '-g', gid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('gid') == gid def chshell(name, shell): ''' Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if shell == pre_info['shell']: return True cmd = ['pw', 'usermod', '-s', shell, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('shell') == shell def chhome(name, home, persist=False): ''' Set a new home directory for an existing user name Username to modify home New home directory to set persist : False Set to ``True`` to prevent configuration files in the new home directory from being overwritten by the files from the skeleton directory. CLI Example: .. code-block:: bash salt '*' user.chhome foo /home/users/foo True ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if home == pre_info['home']: return True cmd = ['pw', 'usermod', name, '-d', home] if persist: cmd.append('-m') __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('home') == home def chgroups(name, groups, append=False): ''' Change the groups to which a user belongs name Username to modify groups List of groups to set for the user. Can be passed as a comma-separated list or a Python list. append : False Set to ``True`` to append these groups to the user's existing list of groups. Otherwise, the specified groups will replace any existing groups for the user. CLI Example: .. code-block:: bash salt '*' user.chgroups foo wheel,root True ''' if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if ugrps == set(groups): return True if append: groups += ugrps cmd = ['pw', 'usermod', '-G', ','.join(groups), '-n', name] return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 def chfullname(name, fullname): ''' Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo "Foo Bar" ''' return _update_gecos(name, 'fullname', fullname) def chroomnumber(name, roomnumber): ''' Change the user's Room Number CLI Example: .. code-block:: bash salt '*' user.chroomnumber foo 123 ''' return _update_gecos(name, 'roomnumber', roomnumber) def chworkphone(name, workphone): ''' Change the user's Work Phone CLI Example: .. code-block:: bash salt '*' user.chworkphone foo "7735550123" ''' return _update_gecos(name, 'workphone', workphone) def chhomephone(name, homephone): ''' Change the user's Home Phone CLI Example: .. code-block:: bash salt '*' user.chhomephone foo "7735551234" ''' return _update_gecos(name, 'homephone', homephone) def chloginclass(name, loginclass, root=None): ''' Change the default login class of the user .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff ''' if loginclass == get_loginclass(name): return True cmd = ['pw', 'usermod', '-L', '{0}'.format(loginclass), '-n', '{0}'.format(name)] __salt__['cmd.run'](cmd, python_shell=False) return get_loginclass(name) == loginclass def info(name): ''' Return user information CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} try: data = pwd.getpwnam(name) ret['gid'] = data.pw_gid ret['groups'] = list_groups(name) ret['home'] = data.pw_dir ret['name'] = data.pw_name ret['passwd'] = data.pw_passwd ret['shell'] = data.pw_shell ret['uid'] = data.pw_uid # Put GECOS info into a list gecos_field = data.pw_gecos.split(',', 3) # Assign empty strings for any unspecified GECOS fields while len(gecos_field) < 4: gecos_field.append('') ret['fullname'] = gecos_field[0] ret['roomnumber'] = gecos_field[1] ret['workphone'] = gecos_field[2] ret['homephone'] = gecos_field[3] except KeyError: return {} return ret def get_loginclass(name): ''' Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' userinfo = __salt__['cmd.run_stdout'](['pw', 'usershow', '-n', name]) userinfo = userinfo.split(':') return userinfo[4] if len(userinfo) == 10 else '' def list_groups(name): ''' Return a list of groups the named user belongs to CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' return salt.utils.user.get_group_list(name) def list_users(): ''' Return a list of all users CLI Example: .. code-block:: bash salt '*' user.list_users ''' return sorted([user.pw_name for user in pwd.getpwall()])
saltstack/salt
salt/proxy/nxos_api.py
init
python
def init(opts): ''' Open the connection to the Nexsu switch over the NX-API. As the communication is HTTP based, there is no connection to maintain, however, in order to test the connectivity and make sure we are able to bring up this Minion, we are executing a very simple command (``show clock``) which doesn't come with much overhead and it's sufficient to confirm we are indeed able to connect to the NX-API endpoint as configured. ''' proxy_dict = opts.get('proxy', {}) conn_args = copy.deepcopy(proxy_dict) conn_args.pop('proxytype', None) opts['multiprocessing'] = conn_args.pop('multiprocessing', True) # This is not a SSH-based proxy, so it should be safe to enable # multiprocessing. try: rpc_reply = __utils__['nxos_api.rpc']('show clock', **conn_args) # Execute a very simple command to confirm we are able to connect properly nxos_device['conn_args'] = conn_args nxos_device['initialized'] = True nxos_device['up'] = True except SaltException: log.error('Unable to connect to %s', conn_args['host'], exc_info=True) raise return True
Open the connection to the Nexsu switch over the NX-API. As the communication is HTTP based, there is no connection to maintain, however, in order to test the connectivity and make sure we are able to bring up this Minion, we are executing a very simple command (``show clock``) which doesn't come with much overhead and it's sufficient to confirm we are indeed able to connect to the NX-API endpoint as configured.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/nxos_api.py#L142-L167
null
# -*- coding: utf-8 -*- ''' Proxy Minion to manage Cisco Nexus Switches (NX-OS) over the NX-API .. versionadded:: 2019.2.0 Proxy module for managing Cisco Nexus switches via the NX-API. :codeauthor: Mircea Ulinic <ping@mirceaulinic.net> :maturity: new :platform: any Usage ===== .. note:: To be able to use this module you need to enable to NX-API on your switch, by executing ``feature nxapi`` in configuration mode. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 .. note:: NX-API requires modern NXOS distributions, typically at least 7.0 depending on the hardware. Due to reliability reasons it is recommended to run the most recent version. Check https://www.cisco.com/c/en/us/td/docs/switches/datacenter/nexus7000/sw/programmability/guide/b_Cisco_Nexus_7000_Series_NX-OS_Programmability_Guide/b_Cisco_Nexus_7000_Series_NX-OS_Programmability_Guide_chapter_0101.html for more details. Pillar ------ The ``nxos_api`` proxy configuration requires the following parameters in order to connect to the network switch: transport: ``https`` Specifies the type of connection transport to use. Valid values for the connection are ``http``, and ``https``. host: ``localhost`` The IP address or DNS host name of the connection device. username: ``admin`` The username to pass to the device to authenticate the NX-API connection. password The password to pass to the device to authenticate the NX-API connection. port The TCP port of the endpoint for the NX-API connection. If this keyword is not specified, the default value is automatically determined by the transport type (``80`` for ``http``, or ``443`` for ``https``). timeout: ``60`` Time in seconds to wait for the device to respond. Default: 60 seconds. verify: ``True`` Either a boolean, in which case it controls whether we verify the NX-API TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. When there is no certificate configuration on the device and this option is set as ``True`` (default), the commands will fail with the following error: ``SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)``. In this case, you either need to configure a proper certificate on the device (*recommended*), or bypass the checks setting this argument as ``False`` with all the security risks considered. Check https://www.cisco.com/c/en/us/td/docs/switches/datacenter/nexus3000/sw/programmability/6_x/b_Cisco_Nexus_3000_Series_NX-OS_Programmability_Guide/b_Cisco_Nexus_3000_Series_NX-OS_Programmability_Guide_chapter_01.html to see how to properly configure the certificate. All the arguments may be optional, depending on your setup. Proxy Pillar Example -------------------- .. code-block:: yaml proxy: proxytype: nxos_api host: switch1.example.com username: example password: example ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import copy import logging # Import Salt modules from salt.exceptions import SaltException # ----------------------------------------------------------------------------- # proxy properties # ----------------------------------------------------------------------------- __proxyenabled__ = ['nxos_api'] # proxy name # ----------------------------------------------------------------------------- # globals # ----------------------------------------------------------------------------- __virtualname__ = 'nxos_api' log = logging.getLogger(__name__) nxos_device = {} # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' This Proxy Module is widely available as there are no external dependencies. ''' return __virtualname__ # ----------------------------------------------------------------------------- # proxy functions # ----------------------------------------------------------------------------- def ping(): ''' Connection open successfully? ''' return nxos_device.get('up', False) def initialized(): ''' Connection finished initializing? ''' return nxos_device.get('initialized', False) def shutdown(opts): ''' Closes connection with the device. ''' log.debug('Shutting down the nxos_api Proxy Minion %s', opts['id']) # ----------------------------------------------------------------------------- # callable functions # ----------------------------------------------------------------------------- def get_conn_args(): ''' Returns the connection arguments of the Proxy Minion. ''' conn_args = copy.deepcopy(nxos_device['conn_args']) return conn_args def rpc(commands, method='cli', **kwargs): ''' Executes an RPC request over the NX-API. ''' conn_args = nxos_device['conn_args'] conn_args.update(kwargs) return __utils__['nxos_api.rpc'](commands, method=method, **conn_args)
saltstack/salt
salt/proxy/nxos_api.py
rpc
python
def rpc(commands, method='cli', **kwargs): ''' Executes an RPC request over the NX-API. ''' conn_args = nxos_device['conn_args'] conn_args.update(kwargs) return __utils__['nxos_api.rpc'](commands, method=method, **conn_args)
Executes an RPC request over the NX-API.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/nxos_api.py#L203-L209
null
# -*- coding: utf-8 -*- ''' Proxy Minion to manage Cisco Nexus Switches (NX-OS) over the NX-API .. versionadded:: 2019.2.0 Proxy module for managing Cisco Nexus switches via the NX-API. :codeauthor: Mircea Ulinic <ping@mirceaulinic.net> :maturity: new :platform: any Usage ===== .. note:: To be able to use this module you need to enable to NX-API on your switch, by executing ``feature nxapi`` in configuration mode. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 .. note:: NX-API requires modern NXOS distributions, typically at least 7.0 depending on the hardware. Due to reliability reasons it is recommended to run the most recent version. Check https://www.cisco.com/c/en/us/td/docs/switches/datacenter/nexus7000/sw/programmability/guide/b_Cisco_Nexus_7000_Series_NX-OS_Programmability_Guide/b_Cisco_Nexus_7000_Series_NX-OS_Programmability_Guide_chapter_0101.html for more details. Pillar ------ The ``nxos_api`` proxy configuration requires the following parameters in order to connect to the network switch: transport: ``https`` Specifies the type of connection transport to use. Valid values for the connection are ``http``, and ``https``. host: ``localhost`` The IP address or DNS host name of the connection device. username: ``admin`` The username to pass to the device to authenticate the NX-API connection. password The password to pass to the device to authenticate the NX-API connection. port The TCP port of the endpoint for the NX-API connection. If this keyword is not specified, the default value is automatically determined by the transport type (``80`` for ``http``, or ``443`` for ``https``). timeout: ``60`` Time in seconds to wait for the device to respond. Default: 60 seconds. verify: ``True`` Either a boolean, in which case it controls whether we verify the NX-API TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. When there is no certificate configuration on the device and this option is set as ``True`` (default), the commands will fail with the following error: ``SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)``. In this case, you either need to configure a proper certificate on the device (*recommended*), or bypass the checks setting this argument as ``False`` with all the security risks considered. Check https://www.cisco.com/c/en/us/td/docs/switches/datacenter/nexus3000/sw/programmability/6_x/b_Cisco_Nexus_3000_Series_NX-OS_Programmability_Guide/b_Cisco_Nexus_3000_Series_NX-OS_Programmability_Guide_chapter_01.html to see how to properly configure the certificate. All the arguments may be optional, depending on your setup. Proxy Pillar Example -------------------- .. code-block:: yaml proxy: proxytype: nxos_api host: switch1.example.com username: example password: example ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import copy import logging # Import Salt modules from salt.exceptions import SaltException # ----------------------------------------------------------------------------- # proxy properties # ----------------------------------------------------------------------------- __proxyenabled__ = ['nxos_api'] # proxy name # ----------------------------------------------------------------------------- # globals # ----------------------------------------------------------------------------- __virtualname__ = 'nxos_api' log = logging.getLogger(__name__) nxos_device = {} # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' This Proxy Module is widely available as there are no external dependencies. ''' return __virtualname__ # ----------------------------------------------------------------------------- # proxy functions # ----------------------------------------------------------------------------- def init(opts): ''' Open the connection to the Nexsu switch over the NX-API. As the communication is HTTP based, there is no connection to maintain, however, in order to test the connectivity and make sure we are able to bring up this Minion, we are executing a very simple command (``show clock``) which doesn't come with much overhead and it's sufficient to confirm we are indeed able to connect to the NX-API endpoint as configured. ''' proxy_dict = opts.get('proxy', {}) conn_args = copy.deepcopy(proxy_dict) conn_args.pop('proxytype', None) opts['multiprocessing'] = conn_args.pop('multiprocessing', True) # This is not a SSH-based proxy, so it should be safe to enable # multiprocessing. try: rpc_reply = __utils__['nxos_api.rpc']('show clock', **conn_args) # Execute a very simple command to confirm we are able to connect properly nxos_device['conn_args'] = conn_args nxos_device['initialized'] = True nxos_device['up'] = True except SaltException: log.error('Unable to connect to %s', conn_args['host'], exc_info=True) raise return True def ping(): ''' Connection open successfully? ''' return nxos_device.get('up', False) def initialized(): ''' Connection finished initializing? ''' return nxos_device.get('initialized', False) def shutdown(opts): ''' Closes connection with the device. ''' log.debug('Shutting down the nxos_api Proxy Minion %s', opts['id']) # ----------------------------------------------------------------------------- # callable functions # ----------------------------------------------------------------------------- def get_conn_args(): ''' Returns the connection arguments of the Proxy Minion. ''' conn_args = copy.deepcopy(nxos_device['conn_args']) return conn_args
saltstack/salt
salt/cloud/__init__.py
communicator
python
def communicator(func): '''Warning, this is a picklable decorator !''' def _call(queue, args, kwargs): '''called with [queue, args, kwargs] as first optional arg''' kwargs['queue'] = queue ret = None try: ret = func(*args, **kwargs) queue.put('END') except KeyboardInterrupt as ex: trace = traceback.format_exc() queue.put('KEYBOARDINT') queue.put('Keyboard interrupt') queue.put('{0}\n{1}\n'.format(ex, trace)) except Exception as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('Exception') queue.put('{0}\n{1}\n'.format(ex, trace)) except SystemExit as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('System exit') queue.put('{0}\n{1}\n'.format(ex, trace)) return ret return _call
Warning, this is a picklable decorator !
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L60-L85
null
# -*- coding: utf-8 -*- ''' The top level interface used to translate configuration data back to the correct cloud modules ''' # Import python libs from __future__ import absolute_import, print_function, generators, unicode_literals import os import copy import glob import time import signal import logging import traceback import multiprocessing import sys from itertools import groupby # Import salt.cloud libs from salt.exceptions import ( SaltCloudNotFound, SaltCloudException, SaltCloudSystemExit, SaltCloudConfigError ) # Import salt libs import salt.config import salt.client import salt.loader import salt.utils.args import salt.utils.cloud import salt.utils.context import salt.utils.crypt import salt.utils.data import salt.utils.dictupdate import salt.utils.files import salt.utils.verify import salt.utils.yaml import salt.utils.user import salt.syspaths from salt.template import compile_template # Import third party libs try: import Cryptodome.Random except ImportError: try: import Crypto.Random except ImportError: pass # pycrypto < 2.1 from salt.ext import six from salt.ext.six.moves import input # pylint: disable=import-error,redefined-builtin # Get logging started log = logging.getLogger(__name__) def enter_mainloop(target, mapped_args=None, args=None, kwargs=None, pool=None, pool_size=None, callback=None, queue=None): ''' Manage a multiprocessing pool - If the queue does not output anything, the pool runs indefinitely - If the queue returns KEYBOARDINT or ERROR, this will kill the pool totally calling terminate & join and ands with a SaltCloudSystemExit exception notifying callers from the abnormal termination - If the queue returns END or callback is defined and returns True, it just join the process and return the data. target the function you want to execute in multiproccessing pool pool object can be None if you want a default pool, but you ll have then to define pool_size instead pool_size pool size if you did not provide yourself a pool callback a boolean taking a string in argument which returns True to signal that 'target' is finished and we need to join the pool queue A custom multiproccessing queue in case you want to do extra stuff and need it later in your program args positional arguments to call the function with if you don't want to use pool.map mapped_args a list of one or more arguments combinations to call the function with e.g. (foo, [[1], [2]]) will call:: foo([1]) foo([2]) kwargs kwargs to give to the function in case of process Attention, the function must have the following signature: target(queue, *args, **kw) You may use the 'communicator' decorator to generate such a function (see end of this file) ''' if not kwargs: kwargs = {} if not pool_size: pool_size = 1 if not pool: pool = multiprocessing.Pool(pool_size) if not queue: manager = multiprocessing.Manager() queue = manager.Queue() if mapped_args is not None and not mapped_args: msg = ( 'We are called to asynchronously execute {0}' ' but we do no have anything to execute, weird,' ' we bail out'.format(target)) log.error(msg) raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif mapped_args is not None: iterable = [[queue, [arg], kwargs] for arg in mapped_args] ret = pool.map(func=target, iterable=iterable) else: ret = pool.apply(target, [queue, args, kwargs]) while True: test = queue.get() if test in ['ERROR', 'KEYBOARDINT']: type_ = queue.get() trace = queue.get() msg = 'Caught {0}, terminating workers\n'.format(type_) msg += 'TRACE: {0}\n'.format(trace) log.error(msg) pool.terminate() pool.join() raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif test in ['END'] or (callback and callback(test)): pool.close() pool.join() break else: time.sleep(0.125) return ret class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' ) class Cloud(object): ''' An object for the creation of new VMs ''' def __init__(self, opts): self.opts = opts self.client = CloudClient(opts=self.opts) self.clouds = salt.loader.clouds(self.opts) self.__filter_non_working_providers() self.__cached_provider_queries = {} def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output def get_running_by_names(self, names, query='list_nodes', cached=False, profile=None): if isinstance(names, six.string_types): names = [names] matches = {} handled_drivers = {} mapped_providers = self.map_providers_parallel(query, cached=cached) for alias, drivers in six.iteritems(mapped_providers): for driver, vms in six.iteritems(drivers): if driver not in handled_drivers: handled_drivers[driver] = alias # When a profile is specified, only return an instance # that matches the provider specified in the profile. # This solves the issues when many providers return the # same instance. For example there may be one provider for # each availability zone in amazon in the same region, but # the search returns the same instance for each provider # because amazon returns all instances in a region, not # availability zone. if profile and alias not in self.opts['profiles'][profile]['provider'].split(':')[0]: continue for vm_name, details in six.iteritems(vms): # XXX: The logic below can be removed once the aws driver # is removed if vm_name not in names: continue elif driver == 'ec2' and 'aws' in handled_drivers and \ 'aws' in matches[handled_drivers['aws']] and \ vm_name in matches[handled_drivers['aws']]['aws']: continue elif driver == 'aws' and 'ec2' in handled_drivers and \ 'ec2' in matches[handled_drivers['ec2']] and \ vm_name in matches[handled_drivers['ec2']]['ec2']: continue if alias not in matches: matches[alias] = {} if driver not in matches[alias]: matches[alias][driver] = {} matches[alias][driver][vm_name] = details return matches def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers def location_list(self, lookup='all'): ''' Return a mapping of all location data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_locations'.format(driver) if fun not in self.clouds: # The capability to gather locations is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the locations information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def size_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_sizes'.format(driver) if fun not in self.clouds: # The capability to gather sizes is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the sizes information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output @staticmethod def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret def do_function(self, prov, func, kwargs): ''' Perform a function against a cloud provider ''' matches = self.lookup_providers(prov) if len(matches) > 1: raise SaltCloudSystemExit( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}'.format( prov, ', '.join([ '{0}:{1}'.format(alias, driver) for (alias, driver) in matches ]) ) ) alias, driver = matches.pop() fun = '{0}.{1}'.format(driver, func) if fun not in self.clouds: raise SaltCloudSystemExit( 'The \'{0}\' cloud provider alias, for the \'{1}\' driver, does ' 'not define the function \'{2}\''.format(alias, driver, func) ) log.debug( 'Trying to execute \'%s\' with the following kwargs: %s', fun, kwargs ) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if kwargs: return { alias: { driver: self.clouds[fun]( call='function', kwargs=kwargs ) } } return { alias: { driver: self.clouds[fun](call='function') } } def __filter_non_working_providers(self): ''' Remove any mis-configured cloud providers from the available listing ''' for alias, drivers in six.iteritems(self.opts['providers'].copy()): for driver in drivers.copy(): fun = '{0}.get_configured_provider'.format(driver) if fun not in self.clouds: # Mis-configured provider that got removed? log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias, could not be loaded. ' 'Please check your provider configuration files and ' 'ensure all required dependencies are installed ' 'for the \'%s\' driver.\n' 'In rare cases, this could indicate the \'%s()\' ' 'function could not be found.\nRemoving \'%s\' from ' 'the available providers list', driver, alias, driver, fun, driver ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if self.clouds[fun]() is False: log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias is not properly ' 'configured. Removing it from the available ' 'providers list.', driver, alias ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) class Map(Cloud): ''' Create a VM stateful map execution object ''' def __init__(self, opts): Cloud.__init__(self, opts) self.rendered_map = self.read() def interpolated_map(self, query='list_nodes', cached=False): rendered_map = self.read().copy() interpolated_map = {} for profile, mapped_vms in six.iteritems(rendered_map): names = set(mapped_vms) if profile not in self.opts['profiles']: if 'Errors' not in interpolated_map: interpolated_map['Errors'] = {} msg = ( 'No provider for the mapped \'{0}\' profile was found. ' 'Skipped VMS: {1}'.format( profile, ', '.join(names) ) ) log.info(msg) interpolated_map['Errors'][profile] = msg continue matching = self.get_running_by_names(names, query, cached) for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for vm_name, vm_details in six.iteritems(vms): if alias not in interpolated_map: interpolated_map[alias] = {} if driver not in interpolated_map[alias]: interpolated_map[alias][driver] = {} interpolated_map[alias][driver][vm_name] = vm_details try: names.remove(vm_name) except KeyError: # If it's not there, then our job is already done pass if not names: continue profile_details = self.opts['profiles'][profile] alias, driver = profile_details['provider'].split(':') for vm_name in names: if alias not in interpolated_map: interpolated_map[alias] = {} if driver not in interpolated_map[alias]: interpolated_map[alias][driver] = {} interpolated_map[alias][driver][vm_name] = 'Absent' return interpolated_map def delete_map(self, query=None): query_map = self.interpolated_map(query=query) for alias, drivers in six.iteritems(query_map.copy()): for driver, vms in six.iteritems(drivers.copy()): for vm_name, vm_details in six.iteritems(vms.copy()): if vm_details == 'Absent': query_map[alias][driver].pop(vm_name) if not query_map[alias][driver]: query_map[alias].pop(driver) if not query_map[alias]: query_map.pop(alias) return query_map def get_vmnames_by_action(self, action): query_map = self.interpolated_map("list_nodes") matching_states = { 'start': ['stopped'], 'stop': ['running', 'active'], 'reboot': ['running', 'active'], } vm_names = [] for alias, drivers in six.iteritems(query_map): for driver, vms in six.iteritems(drivers): for vm_name, vm_details in six.iteritems(vms): # Only certain actions are support in to use in this case. Those actions are the # "Global" salt-cloud actions defined in the "matching_states" dictionary above. # If a more specific action is passed in, we shouldn't stack-trace - exit gracefully. try: state_action = matching_states[action] except KeyError: log.error( 'The use of \'%s\' as an action is not supported ' 'in this context. Only \'start\', \'stop\', and ' '\'reboot\' are supported options.', action ) raise SaltCloudException() if vm_details != 'Absent' and vm_details['state'].lower() in state_action: vm_names.append(vm_name) return vm_names def read(self): ''' Read in the specified map and return the map structure ''' map_ = None if self.opts.get('map', None) is None: if self.opts.get('map_data', None) is None: if self.opts.get('map_pillar', None) is None: pass elif self.opts.get('map_pillar') not in self.opts.get('maps'): log.error( 'The specified map not found in pillar at ' '\'cloud:maps:%s\'', self.opts['map_pillar'] ) raise SaltCloudNotFound() else: # 'map_pillar' is provided, try to use it map_ = self.opts['maps'][self.opts.get('map_pillar')] else: # 'map_data' is provided, try to use it map_ = self.opts['map_data'] else: # 'map' is provided, try to use it local_minion_opts = copy.deepcopy(self.opts) local_minion_opts['file_client'] = 'local' self.minion = salt.minion.MasterMinion(local_minion_opts) if not os.path.isfile(self.opts['map']): if not (self.opts['map']).startswith('salt://'): log.error( 'The specified map file does not exist: \'%s\'', self.opts['map'] ) raise SaltCloudNotFound() if (self.opts['map']).startswith('salt://'): cached_map = self.minion.functions['cp.cache_file'](self.opts['map']) else: cached_map = self.opts['map'] try: renderer = self.opts.get('renderer', 'jinja|yaml') rend = salt.loader.render(self.opts, {}) blacklist = self.opts.get('renderer_blacklist') whitelist = self.opts.get('renderer_whitelist') map_ = compile_template( cached_map, rend, renderer, blacklist, whitelist ) except Exception as exc: log.error( 'Rendering map %s failed, render error:\n%s', self.opts['map'], exc, exc_info_on_loglevel=logging.DEBUG ) return {} if 'include' in map_: map_ = salt.config.include_config( map_, self.opts['map'], verbose=False ) if not map_: return {} # Create expected data format if needed for profile, mapped in six.iteritems(map_.copy()): if isinstance(mapped, (list, tuple)): entries = {} for mapping in mapped: if isinstance(mapping, six.string_types): # Foo: # - bar1 # - bar2 mapping = {mapping: None} for name, overrides in six.iteritems(mapping): if overrides is None or isinstance(overrides, bool): # Foo: # - bar1: # - bar2: overrides = {} try: overrides.setdefault('name', name) except AttributeError: log.error( 'Cannot use \'name\' as a minion id in a cloud map as it ' 'is a reserved word. Please change \'name\' to a different ' 'minion id reference.' ) return {} entries[name] = overrides map_[profile] = entries continue if isinstance(mapped, dict): # Convert the dictionary mapping to a list of dictionaries # Foo: # bar1: # grains: # foo: bar # bar2: # grains: # foo: bar entries = {} for name, overrides in six.iteritems(mapped): overrides.setdefault('name', name) entries[name] = overrides map_[profile] = entries continue if isinstance(mapped, six.string_types): # If it's a single string entry, let's make iterable because of # the next step mapped = [mapped] map_[profile] = {} for name in mapped: map_[profile][name] = {'name': name} return map_ def _has_loop(self, dmap, seen=None, val=None): if seen is None: for values in six.itervalues(dmap['create']): seen = [] try: machines = values['requires'] except KeyError: machines = [] for machine in machines: if self._has_loop(dmap, seen=list(seen), val=machine): return True else: if val in seen: return True seen.append(val) try: machines = dmap['create'][val]['requires'] except KeyError: machines = [] for machine in machines: if self._has_loop(dmap, seen=list(seen), val=machine): return True return False def _calcdep(self, dmap, machine, data, level): try: deplist = data['requires'] except KeyError: return level levels = [] for name in deplist: try: data = dmap['create'][name] except KeyError: try: data = dmap['existing'][name] except KeyError: msg = 'Missing dependency in cloud map' log.error(msg) raise SaltCloudException(msg) levels.append(self._calcdep(dmap, name, data, level)) level = max(levels) + 1 return level def map_data(self, cached=False): ''' Create a data map of what to execute on ''' ret = {'create': {}} pmap = self.map_providers_parallel(cached=cached) exist = set() defined = set() rendered_map = copy.deepcopy(self.rendered_map) for profile_name, nodes in six.iteritems(rendered_map): if profile_name not in self.opts['profiles']: msg = ( 'The required profile, \'{0}\', defined in the map ' 'does not exist. The defined nodes, {1}, will not ' 'be created.'.format( profile_name, ', '.join('\'{0}\''.format(node) for node in nodes) ) ) log.error(msg) if 'errors' not in ret: ret['errors'] = {} ret['errors'][profile_name] = msg continue profile_data = self.opts['profiles'].get(profile_name) for nodename, overrides in six.iteritems(nodes): # Get associated provider data, in case something like size # or image is specified in the provider file. See issue #32510. if 'provider' in overrides and overrides['provider'] != profile_data['provider']: alias, driver = overrides.get('provider').split(':') else: alias, driver = profile_data.get('provider').split(':') provider_details = copy.deepcopy(self.opts['providers'][alias][driver]) del provider_details['profiles'] # Update the provider details information with profile data # Profile data and node overrides should override provider data, if defined. # This keeps map file data definitions consistent with -p usage. salt.utils.dictupdate.update(provider_details, profile_data) nodedata = copy.deepcopy(provider_details) # Update profile data with the map overrides for setting in ('grains', 'master', 'minion', 'volumes', 'requires'): deprecated = 'map_{0}'.format(setting) if deprecated in overrides: log.warning( 'The use of \'%s\' on the \'%s\' mapping has ' 'been deprecated. The preferred way now is to ' 'just define \'%s\'. For now, salt-cloud will do ' 'the proper thing and convert the deprecated ' 'mapping into the preferred one.', deprecated, nodename, setting ) overrides[setting] = overrides.pop(deprecated) # merge minion grains from map file if 'minion' in overrides and \ 'minion' in nodedata and \ 'grains' in overrides['minion'] and \ 'grains' in nodedata['minion']: nodedata['minion']['grains'].update( overrides['minion']['grains'] ) del overrides['minion']['grains'] # remove minion key if now is empty dict if not overrides['minion']: del overrides['minion'] nodedata = salt.utils.dictupdate.update(nodedata, overrides) # Add the computed information to the return data ret['create'][nodename] = nodedata # Add the node name to the defined set alias, driver = nodedata['provider'].split(':') defined.add((alias, driver, nodename)) def get_matching_by_name(name): matches = {} for alias, drivers in six.iteritems(pmap): for driver, vms in six.iteritems(drivers): for vm_name, details in six.iteritems(vms): if vm_name == name and driver not in matches: matches[driver] = details['state'] return matches for alias, drivers in six.iteritems(pmap): for driver, vms in six.iteritems(drivers): for name, details in six.iteritems(vms): exist.add((alias, driver, name)) if name not in ret['create']: continue # The machine is set to be created. Does it already exist? matching = get_matching_by_name(name) if not matching: continue # A machine by the same name exists for item in matching: if name not in ret['create']: # Machine already removed break log.warning("'%s' already exists, removing from " 'the create map.', name) if 'existing' not in ret: ret['existing'] = {} ret['existing'][name] = ret['create'].pop(name) if 'hard' in self.opts and self.opts['hard']: if self.opts['enable_hard_maps'] is False: raise SaltCloudSystemExit( 'The --hard map can be extremely dangerous to use, ' 'and therefore must explicitly be enabled in the main ' 'configuration file, by setting \'enable_hard_maps\' ' 'to True' ) # Hard maps are enabled, Look for the items to delete. ret['destroy'] = exist.difference(defined) return ret def run_map(self, dmap): ''' Execute the contents of the VM map ''' if self._has_loop(dmap): msg = 'Uh-oh, that cloud map has a dependency loop!' log.error(msg) raise SaltCloudException(msg) # Go through the create list and calc dependencies for key, val in six.iteritems(dmap['create']): log.info('Calculating dependencies for %s', key) level = 0 level = self._calcdep(dmap, key, val, level) log.debug('Got execution order %s for %s', level, key) dmap['create'][key]['level'] = level try: existing_list = six.iteritems(dmap['existing']) except KeyError: existing_list = six.iteritems({}) for key, val in existing_list: log.info('Calculating dependencies for %s', key) level = 0 level = self._calcdep(dmap, key, val, level) log.debug('Got execution order %s for %s', level, key) dmap['existing'][key]['level'] = level # Now sort the create list based on dependencies create_list = sorted(six.iteritems(dmap['create']), key=lambda x: x[1]['level']) full_map = dmap['create'].copy() if 'existing' in dmap: full_map.update(dmap['existing']) possible_master_list = sorted(six.iteritems(full_map), key=lambda x: x[1]['level']) output = {} if self.opts['parallel']: parallel_data = [] master_name = None master_minion_name = None master_host = None master_finger = None for name, profile in possible_master_list: if profile.get('make_master', False) is True: master_name = name master_profile = profile if master_name: # If the master already exists, get the host if master_name not in dmap['create']: master_host = self.client.query() for provider_part in master_profile['provider'].split(':'): master_host = master_host[provider_part] master_host = master_host[master_name][master_profile.get('ssh_interface', 'public_ips')] if not master_host: raise SaltCloudSystemExit( 'Could not get the hostname of master {}.'.format(master_name) ) # Otherwise, deploy it as a new master else: master_minion_name = master_name log.debug('Creating new master \'%s\'', master_name) if salt.config.get_cloud_config_value( 'deploy', master_profile, self.opts ) is False: raise SaltCloudSystemExit( 'Cannot proceed with \'make_master\' when salt deployment ' 'is disabled(ex: --no-deploy).' ) # Generate the master keys log.debug('Generating master keys for \'%s\'', master_profile['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', master_profile, self.opts ) ) master_profile['master_pub'] = pub master_profile['master_pem'] = priv # Generate the fingerprint of the master pubkey in order to # mitigate man-in-the-middle attacks master_temp_pub = salt.utils.files.mkstemp() with salt.utils.files.fopen(master_temp_pub, 'w') as mtp: mtp.write(pub) master_finger = salt.utils.crypt.pem_finger(master_temp_pub, sum_type=self.opts['hash_type']) os.unlink(master_temp_pub) if master_profile.get('make_minion', True) is True: master_profile.setdefault('minion', {}) if 'id' in master_profile['minion']: master_minion_name = master_profile['minion']['id'] # Set this minion's master as local if the user has not set it if 'master' not in master_profile['minion']: master_profile['minion']['master'] = '127.0.0.1' if master_finger is not None: master_profile['master_finger'] = master_finger # Generate the minion keys to pre-seed the master: for name, profile in create_list: make_minion = salt.config.get_cloud_config_value( 'make_minion', profile, self.opts, default=True ) if make_minion is False: continue log.debug('Generating minion keys for \'%s\'', profile['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', profile, self.opts ) ) profile['pub_key'] = pub profile['priv_key'] = priv # Store the minion's public key in order to be pre-seeded in # the master master_profile.setdefault('preseed_minion_keys', {}) master_profile['preseed_minion_keys'].update({name: pub}) local_master = False if master_profile['minion'].get('local_master', False) and \ master_profile['minion'].get('master', None) is not None: # The minion is explicitly defining a master and it's # explicitly saying it's the local one local_master = True out = self.create(master_profile, local_master=local_master) if not isinstance(out, dict): log.debug('Master creation details is not a dictionary: %s', out) elif 'Errors' in out: raise SaltCloudSystemExit( 'An error occurred while creating the master, not ' 'continuing: {0}'.format(out['Errors']) ) deploy_kwargs = ( self.opts.get('show_deploy_args', False) is True and # Get the needed data out.get('deploy_kwargs', {}) or # Strip the deploy_kwargs from the returned data since we don't # want it shown in the console. out.pop('deploy_kwargs', {}) ) master_host = deploy_kwargs.get('salt_host', deploy_kwargs.get('host', None)) if master_host is None: raise SaltCloudSystemExit( 'Host for new master {0} was not found, ' 'aborting map'.format( master_name ) ) output[master_name] = out else: log.debug('No make_master found in map') # Local master? # Generate the fingerprint of the master pubkey in order to # mitigate man-in-the-middle attacks master_pub = os.path.join(self.opts['pki_dir'], 'master.pub') if os.path.isfile(master_pub): master_finger = salt.utils.crypt.pem_finger(master_pub, sum_type=self.opts['hash_type']) opts = self.opts.copy() if self.opts['parallel']: # Force display_ssh_output to be False since the console will # need to be reset afterwards log.info( 'Since parallel deployment is in use, ssh console output ' 'is disabled. All ssh output will be logged though' ) opts['display_ssh_output'] = False local_master = master_name is None for name, profile in create_list: if name in (master_name, master_minion_name): # Already deployed, it's the master's minion continue if 'minion' in profile and profile['minion'].get('local_master', False) and \ profile['minion'].get('master', None) is not None: # The minion is explicitly defining a master and it's # explicitly saying it's the local one local_master = True if master_finger is not None and local_master is False: profile['master_finger'] = master_finger if master_host is not None: profile.setdefault('minion', {}) profile['minion'].setdefault('master', master_host) if self.opts['parallel']: parallel_data.append({ 'opts': opts, 'name': name, 'profile': profile, 'local_master': local_master }) continue # Not deploying in parallel try: output[name] = self.create( profile, local_master=local_master ) if self.opts.get('show_deploy_args', False) is False \ and 'deploy_kwargs' in output \ and isinstance(output[name], dict): output[name].pop('deploy_kwargs', None) except SaltCloudException as exc: log.error( 'Failed to deploy \'%s\'. Error: %s', name, exc, exc_info_on_loglevel=logging.DEBUG ) output[name] = {'Error': str(exc)} for name in dmap.get('destroy', ()): output[name] = self.destroy(name) if self.opts['parallel'] and parallel_data: if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Cloud pool size: %s', pool_size) output_multip = enter_mainloop( _create_multiprocessing, parallel_data, pool_size=pool_size) # We have deployed in parallel, now do start action in # correct order based on dependencies. if self.opts['start_action']: actionlist = [] grp = -1 for key, val in groupby(six.itervalues(dmap['create']), lambda x: x['level']): actionlist.append([]) grp += 1 for item in val: actionlist[grp].append(item['name']) out = {} for group in actionlist: log.info('Running %s on %s', self.opts['start_action'], ', '.join(group)) client = salt.client.get_local_client() out.update(client.cmd( ','.join(group), self.opts['start_action'], timeout=self.opts['timeout'] * 60, tgt_type='list' )) for obj in output_multip: next(six.itervalues(obj))['ret'] = out[next(six.iterkeys(obj))] output.update(obj) else: for obj in output_multip: output.update(obj) return output def init_pool_worker(): ''' Make every worker ignore KeyboarInterrup's since it will be handled by the parent process. ''' signal.signal(signal.SIGINT, signal.SIG_IGN) def create_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the create is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' cloud = Cloud(parallel_data['opts']) try: output = cloud.create( parallel_data['profile'], local_master=parallel_data['local_master'] ) except SaltCloudException as exc: log.error( 'Failed to deploy \'%s\'. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} if parallel_data['opts'].get('show_deploy_args', False) is False and isinstance(output, dict): output.pop('deploy_kwargs', None) return { parallel_data['name']: salt.utils.data.simple_types_filter(output) } def destroy_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the destroy is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' clouds = salt.loader.clouds(parallel_data['opts']) try: fun = clouds['{0}.destroy'.format(parallel_data['driver'])] with salt.utils.context.func_globals_inject( fun, __active_provider_name__=':'.join([ parallel_data['alias'], parallel_data['driver'] ]) ): output = fun(parallel_data['name']) except SaltCloudException as exc: log.error( 'Failed to destroy %s. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} return { parallel_data['name']: salt.utils.data.simple_types_filter(output) } def run_parallel_map_providers_query(data, queue=None): ''' This function will be called from another process when building the providers map. ''' salt.utils.crypt.reinit_crypto() cloud = Cloud(data['opts']) try: with salt.utils.context.func_globals_inject( cloud.clouds[data['fun']], __active_provider_name__=':'.join([ data['alias'], data['driver'] ]) ): return ( data['alias'], data['driver'], salt.utils.data.simple_types_filter( cloud.clouds[data['fun']]() ) ) except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for running nodes: %s', data['fun'], err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any nodes return data['alias'], data['driver'], () # for pickle and multiprocessing, we can't use directly decorators def _run_parallel_map_providers_query(*args, **kw): return communicator(run_parallel_map_providers_query)(*args[0], **kw) def _destroy_multiprocessing(*args, **kw): return communicator(destroy_multiprocessing)(*args[0], **kw) def _create_multiprocessing(*args, **kw): return communicator(create_multiprocessing)(*args[0], **kw)
saltstack/salt
salt/cloud/__init__.py
enter_mainloop
python
def enter_mainloop(target, mapped_args=None, args=None, kwargs=None, pool=None, pool_size=None, callback=None, queue=None): ''' Manage a multiprocessing pool - If the queue does not output anything, the pool runs indefinitely - If the queue returns KEYBOARDINT or ERROR, this will kill the pool totally calling terminate & join and ands with a SaltCloudSystemExit exception notifying callers from the abnormal termination - If the queue returns END or callback is defined and returns True, it just join the process and return the data. target the function you want to execute in multiproccessing pool pool object can be None if you want a default pool, but you ll have then to define pool_size instead pool_size pool size if you did not provide yourself a pool callback a boolean taking a string in argument which returns True to signal that 'target' is finished and we need to join the pool queue A custom multiproccessing queue in case you want to do extra stuff and need it later in your program args positional arguments to call the function with if you don't want to use pool.map mapped_args a list of one or more arguments combinations to call the function with e.g. (foo, [[1], [2]]) will call:: foo([1]) foo([2]) kwargs kwargs to give to the function in case of process Attention, the function must have the following signature: target(queue, *args, **kw) You may use the 'communicator' decorator to generate such a function (see end of this file) ''' if not kwargs: kwargs = {} if not pool_size: pool_size = 1 if not pool: pool = multiprocessing.Pool(pool_size) if not queue: manager = multiprocessing.Manager() queue = manager.Queue() if mapped_args is not None and not mapped_args: msg = ( 'We are called to asynchronously execute {0}' ' but we do no have anything to execute, weird,' ' we bail out'.format(target)) log.error(msg) raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif mapped_args is not None: iterable = [[queue, [arg], kwargs] for arg in mapped_args] ret = pool.map(func=target, iterable=iterable) else: ret = pool.apply(target, [queue, args, kwargs]) while True: test = queue.get() if test in ['ERROR', 'KEYBOARDINT']: type_ = queue.get() trace = queue.get() msg = 'Caught {0}, terminating workers\n'.format(type_) msg += 'TRACE: {0}\n'.format(trace) log.error(msg) pool.terminate() pool.join() raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif test in ['END'] or (callback and callback(test)): pool.close() pool.join() break else: time.sleep(0.125) return ret
Manage a multiprocessing pool - If the queue does not output anything, the pool runs indefinitely - If the queue returns KEYBOARDINT or ERROR, this will kill the pool totally calling terminate & join and ands with a SaltCloudSystemExit exception notifying callers from the abnormal termination - If the queue returns END or callback is defined and returns True, it just join the process and return the data. target the function you want to execute in multiproccessing pool pool object can be None if you want a default pool, but you ll have then to define pool_size instead pool_size pool size if you did not provide yourself a pool callback a boolean taking a string in argument which returns True to signal that 'target' is finished and we need to join the pool queue A custom multiproccessing queue in case you want to do extra stuff and need it later in your program args positional arguments to call the function with if you don't want to use pool.map mapped_args a list of one or more arguments combinations to call the function with e.g. (foo, [[1], [2]]) will call:: foo([1]) foo([2]) kwargs kwargs to give to the function in case of process Attention, the function must have the following signature: target(queue, *args, **kw) You may use the 'communicator' decorator to generate such a function (see end of this file)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L88-L182
null
# -*- coding: utf-8 -*- ''' The top level interface used to translate configuration data back to the correct cloud modules ''' # Import python libs from __future__ import absolute_import, print_function, generators, unicode_literals import os import copy import glob import time import signal import logging import traceback import multiprocessing import sys from itertools import groupby # Import salt.cloud libs from salt.exceptions import ( SaltCloudNotFound, SaltCloudException, SaltCloudSystemExit, SaltCloudConfigError ) # Import salt libs import salt.config import salt.client import salt.loader import salt.utils.args import salt.utils.cloud import salt.utils.context import salt.utils.crypt import salt.utils.data import salt.utils.dictupdate import salt.utils.files import salt.utils.verify import salt.utils.yaml import salt.utils.user import salt.syspaths from salt.template import compile_template # Import third party libs try: import Cryptodome.Random except ImportError: try: import Crypto.Random except ImportError: pass # pycrypto < 2.1 from salt.ext import six from salt.ext.six.moves import input # pylint: disable=import-error,redefined-builtin # Get logging started log = logging.getLogger(__name__) def communicator(func): '''Warning, this is a picklable decorator !''' def _call(queue, args, kwargs): '''called with [queue, args, kwargs] as first optional arg''' kwargs['queue'] = queue ret = None try: ret = func(*args, **kwargs) queue.put('END') except KeyboardInterrupt as ex: trace = traceback.format_exc() queue.put('KEYBOARDINT') queue.put('Keyboard interrupt') queue.put('{0}\n{1}\n'.format(ex, trace)) except Exception as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('Exception') queue.put('{0}\n{1}\n'.format(ex, trace)) except SystemExit as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('System exit') queue.put('{0}\n{1}\n'.format(ex, trace)) return ret return _call class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' ) class Cloud(object): ''' An object for the creation of new VMs ''' def __init__(self, opts): self.opts = opts self.client = CloudClient(opts=self.opts) self.clouds = salt.loader.clouds(self.opts) self.__filter_non_working_providers() self.__cached_provider_queries = {} def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output def get_running_by_names(self, names, query='list_nodes', cached=False, profile=None): if isinstance(names, six.string_types): names = [names] matches = {} handled_drivers = {} mapped_providers = self.map_providers_parallel(query, cached=cached) for alias, drivers in six.iteritems(mapped_providers): for driver, vms in six.iteritems(drivers): if driver not in handled_drivers: handled_drivers[driver] = alias # When a profile is specified, only return an instance # that matches the provider specified in the profile. # This solves the issues when many providers return the # same instance. For example there may be one provider for # each availability zone in amazon in the same region, but # the search returns the same instance for each provider # because amazon returns all instances in a region, not # availability zone. if profile and alias not in self.opts['profiles'][profile]['provider'].split(':')[0]: continue for vm_name, details in six.iteritems(vms): # XXX: The logic below can be removed once the aws driver # is removed if vm_name not in names: continue elif driver == 'ec2' and 'aws' in handled_drivers and \ 'aws' in matches[handled_drivers['aws']] and \ vm_name in matches[handled_drivers['aws']]['aws']: continue elif driver == 'aws' and 'ec2' in handled_drivers and \ 'ec2' in matches[handled_drivers['ec2']] and \ vm_name in matches[handled_drivers['ec2']]['ec2']: continue if alias not in matches: matches[alias] = {} if driver not in matches[alias]: matches[alias][driver] = {} matches[alias][driver][vm_name] = details return matches def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers def location_list(self, lookup='all'): ''' Return a mapping of all location data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_locations'.format(driver) if fun not in self.clouds: # The capability to gather locations is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the locations information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def size_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_sizes'.format(driver) if fun not in self.clouds: # The capability to gather sizes is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the sizes information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output @staticmethod def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret def do_function(self, prov, func, kwargs): ''' Perform a function against a cloud provider ''' matches = self.lookup_providers(prov) if len(matches) > 1: raise SaltCloudSystemExit( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}'.format( prov, ', '.join([ '{0}:{1}'.format(alias, driver) for (alias, driver) in matches ]) ) ) alias, driver = matches.pop() fun = '{0}.{1}'.format(driver, func) if fun not in self.clouds: raise SaltCloudSystemExit( 'The \'{0}\' cloud provider alias, for the \'{1}\' driver, does ' 'not define the function \'{2}\''.format(alias, driver, func) ) log.debug( 'Trying to execute \'%s\' with the following kwargs: %s', fun, kwargs ) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if kwargs: return { alias: { driver: self.clouds[fun]( call='function', kwargs=kwargs ) } } return { alias: { driver: self.clouds[fun](call='function') } } def __filter_non_working_providers(self): ''' Remove any mis-configured cloud providers from the available listing ''' for alias, drivers in six.iteritems(self.opts['providers'].copy()): for driver in drivers.copy(): fun = '{0}.get_configured_provider'.format(driver) if fun not in self.clouds: # Mis-configured provider that got removed? log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias, could not be loaded. ' 'Please check your provider configuration files and ' 'ensure all required dependencies are installed ' 'for the \'%s\' driver.\n' 'In rare cases, this could indicate the \'%s()\' ' 'function could not be found.\nRemoving \'%s\' from ' 'the available providers list', driver, alias, driver, fun, driver ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if self.clouds[fun]() is False: log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias is not properly ' 'configured. Removing it from the available ' 'providers list.', driver, alias ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) class Map(Cloud): ''' Create a VM stateful map execution object ''' def __init__(self, opts): Cloud.__init__(self, opts) self.rendered_map = self.read() def interpolated_map(self, query='list_nodes', cached=False): rendered_map = self.read().copy() interpolated_map = {} for profile, mapped_vms in six.iteritems(rendered_map): names = set(mapped_vms) if profile not in self.opts['profiles']: if 'Errors' not in interpolated_map: interpolated_map['Errors'] = {} msg = ( 'No provider for the mapped \'{0}\' profile was found. ' 'Skipped VMS: {1}'.format( profile, ', '.join(names) ) ) log.info(msg) interpolated_map['Errors'][profile] = msg continue matching = self.get_running_by_names(names, query, cached) for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for vm_name, vm_details in six.iteritems(vms): if alias not in interpolated_map: interpolated_map[alias] = {} if driver not in interpolated_map[alias]: interpolated_map[alias][driver] = {} interpolated_map[alias][driver][vm_name] = vm_details try: names.remove(vm_name) except KeyError: # If it's not there, then our job is already done pass if not names: continue profile_details = self.opts['profiles'][profile] alias, driver = profile_details['provider'].split(':') for vm_name in names: if alias not in interpolated_map: interpolated_map[alias] = {} if driver not in interpolated_map[alias]: interpolated_map[alias][driver] = {} interpolated_map[alias][driver][vm_name] = 'Absent' return interpolated_map def delete_map(self, query=None): query_map = self.interpolated_map(query=query) for alias, drivers in six.iteritems(query_map.copy()): for driver, vms in six.iteritems(drivers.copy()): for vm_name, vm_details in six.iteritems(vms.copy()): if vm_details == 'Absent': query_map[alias][driver].pop(vm_name) if not query_map[alias][driver]: query_map[alias].pop(driver) if not query_map[alias]: query_map.pop(alias) return query_map def get_vmnames_by_action(self, action): query_map = self.interpolated_map("list_nodes") matching_states = { 'start': ['stopped'], 'stop': ['running', 'active'], 'reboot': ['running', 'active'], } vm_names = [] for alias, drivers in six.iteritems(query_map): for driver, vms in six.iteritems(drivers): for vm_name, vm_details in six.iteritems(vms): # Only certain actions are support in to use in this case. Those actions are the # "Global" salt-cloud actions defined in the "matching_states" dictionary above. # If a more specific action is passed in, we shouldn't stack-trace - exit gracefully. try: state_action = matching_states[action] except KeyError: log.error( 'The use of \'%s\' as an action is not supported ' 'in this context. Only \'start\', \'stop\', and ' '\'reboot\' are supported options.', action ) raise SaltCloudException() if vm_details != 'Absent' and vm_details['state'].lower() in state_action: vm_names.append(vm_name) return vm_names def read(self): ''' Read in the specified map and return the map structure ''' map_ = None if self.opts.get('map', None) is None: if self.opts.get('map_data', None) is None: if self.opts.get('map_pillar', None) is None: pass elif self.opts.get('map_pillar') not in self.opts.get('maps'): log.error( 'The specified map not found in pillar at ' '\'cloud:maps:%s\'', self.opts['map_pillar'] ) raise SaltCloudNotFound() else: # 'map_pillar' is provided, try to use it map_ = self.opts['maps'][self.opts.get('map_pillar')] else: # 'map_data' is provided, try to use it map_ = self.opts['map_data'] else: # 'map' is provided, try to use it local_minion_opts = copy.deepcopy(self.opts) local_minion_opts['file_client'] = 'local' self.minion = salt.minion.MasterMinion(local_minion_opts) if not os.path.isfile(self.opts['map']): if not (self.opts['map']).startswith('salt://'): log.error( 'The specified map file does not exist: \'%s\'', self.opts['map'] ) raise SaltCloudNotFound() if (self.opts['map']).startswith('salt://'): cached_map = self.minion.functions['cp.cache_file'](self.opts['map']) else: cached_map = self.opts['map'] try: renderer = self.opts.get('renderer', 'jinja|yaml') rend = salt.loader.render(self.opts, {}) blacklist = self.opts.get('renderer_blacklist') whitelist = self.opts.get('renderer_whitelist') map_ = compile_template( cached_map, rend, renderer, blacklist, whitelist ) except Exception as exc: log.error( 'Rendering map %s failed, render error:\n%s', self.opts['map'], exc, exc_info_on_loglevel=logging.DEBUG ) return {} if 'include' in map_: map_ = salt.config.include_config( map_, self.opts['map'], verbose=False ) if not map_: return {} # Create expected data format if needed for profile, mapped in six.iteritems(map_.copy()): if isinstance(mapped, (list, tuple)): entries = {} for mapping in mapped: if isinstance(mapping, six.string_types): # Foo: # - bar1 # - bar2 mapping = {mapping: None} for name, overrides in six.iteritems(mapping): if overrides is None or isinstance(overrides, bool): # Foo: # - bar1: # - bar2: overrides = {} try: overrides.setdefault('name', name) except AttributeError: log.error( 'Cannot use \'name\' as a minion id in a cloud map as it ' 'is a reserved word. Please change \'name\' to a different ' 'minion id reference.' ) return {} entries[name] = overrides map_[profile] = entries continue if isinstance(mapped, dict): # Convert the dictionary mapping to a list of dictionaries # Foo: # bar1: # grains: # foo: bar # bar2: # grains: # foo: bar entries = {} for name, overrides in six.iteritems(mapped): overrides.setdefault('name', name) entries[name] = overrides map_[profile] = entries continue if isinstance(mapped, six.string_types): # If it's a single string entry, let's make iterable because of # the next step mapped = [mapped] map_[profile] = {} for name in mapped: map_[profile][name] = {'name': name} return map_ def _has_loop(self, dmap, seen=None, val=None): if seen is None: for values in six.itervalues(dmap['create']): seen = [] try: machines = values['requires'] except KeyError: machines = [] for machine in machines: if self._has_loop(dmap, seen=list(seen), val=machine): return True else: if val in seen: return True seen.append(val) try: machines = dmap['create'][val]['requires'] except KeyError: machines = [] for machine in machines: if self._has_loop(dmap, seen=list(seen), val=machine): return True return False def _calcdep(self, dmap, machine, data, level): try: deplist = data['requires'] except KeyError: return level levels = [] for name in deplist: try: data = dmap['create'][name] except KeyError: try: data = dmap['existing'][name] except KeyError: msg = 'Missing dependency in cloud map' log.error(msg) raise SaltCloudException(msg) levels.append(self._calcdep(dmap, name, data, level)) level = max(levels) + 1 return level def map_data(self, cached=False): ''' Create a data map of what to execute on ''' ret = {'create': {}} pmap = self.map_providers_parallel(cached=cached) exist = set() defined = set() rendered_map = copy.deepcopy(self.rendered_map) for profile_name, nodes in six.iteritems(rendered_map): if profile_name not in self.opts['profiles']: msg = ( 'The required profile, \'{0}\', defined in the map ' 'does not exist. The defined nodes, {1}, will not ' 'be created.'.format( profile_name, ', '.join('\'{0}\''.format(node) for node in nodes) ) ) log.error(msg) if 'errors' not in ret: ret['errors'] = {} ret['errors'][profile_name] = msg continue profile_data = self.opts['profiles'].get(profile_name) for nodename, overrides in six.iteritems(nodes): # Get associated provider data, in case something like size # or image is specified in the provider file. See issue #32510. if 'provider' in overrides and overrides['provider'] != profile_data['provider']: alias, driver = overrides.get('provider').split(':') else: alias, driver = profile_data.get('provider').split(':') provider_details = copy.deepcopy(self.opts['providers'][alias][driver]) del provider_details['profiles'] # Update the provider details information with profile data # Profile data and node overrides should override provider data, if defined. # This keeps map file data definitions consistent with -p usage. salt.utils.dictupdate.update(provider_details, profile_data) nodedata = copy.deepcopy(provider_details) # Update profile data with the map overrides for setting in ('grains', 'master', 'minion', 'volumes', 'requires'): deprecated = 'map_{0}'.format(setting) if deprecated in overrides: log.warning( 'The use of \'%s\' on the \'%s\' mapping has ' 'been deprecated. The preferred way now is to ' 'just define \'%s\'. For now, salt-cloud will do ' 'the proper thing and convert the deprecated ' 'mapping into the preferred one.', deprecated, nodename, setting ) overrides[setting] = overrides.pop(deprecated) # merge minion grains from map file if 'minion' in overrides and \ 'minion' in nodedata and \ 'grains' in overrides['minion'] and \ 'grains' in nodedata['minion']: nodedata['minion']['grains'].update( overrides['minion']['grains'] ) del overrides['minion']['grains'] # remove minion key if now is empty dict if not overrides['minion']: del overrides['minion'] nodedata = salt.utils.dictupdate.update(nodedata, overrides) # Add the computed information to the return data ret['create'][nodename] = nodedata # Add the node name to the defined set alias, driver = nodedata['provider'].split(':') defined.add((alias, driver, nodename)) def get_matching_by_name(name): matches = {} for alias, drivers in six.iteritems(pmap): for driver, vms in six.iteritems(drivers): for vm_name, details in six.iteritems(vms): if vm_name == name and driver not in matches: matches[driver] = details['state'] return matches for alias, drivers in six.iteritems(pmap): for driver, vms in six.iteritems(drivers): for name, details in six.iteritems(vms): exist.add((alias, driver, name)) if name not in ret['create']: continue # The machine is set to be created. Does it already exist? matching = get_matching_by_name(name) if not matching: continue # A machine by the same name exists for item in matching: if name not in ret['create']: # Machine already removed break log.warning("'%s' already exists, removing from " 'the create map.', name) if 'existing' not in ret: ret['existing'] = {} ret['existing'][name] = ret['create'].pop(name) if 'hard' in self.opts and self.opts['hard']: if self.opts['enable_hard_maps'] is False: raise SaltCloudSystemExit( 'The --hard map can be extremely dangerous to use, ' 'and therefore must explicitly be enabled in the main ' 'configuration file, by setting \'enable_hard_maps\' ' 'to True' ) # Hard maps are enabled, Look for the items to delete. ret['destroy'] = exist.difference(defined) return ret def run_map(self, dmap): ''' Execute the contents of the VM map ''' if self._has_loop(dmap): msg = 'Uh-oh, that cloud map has a dependency loop!' log.error(msg) raise SaltCloudException(msg) # Go through the create list and calc dependencies for key, val in six.iteritems(dmap['create']): log.info('Calculating dependencies for %s', key) level = 0 level = self._calcdep(dmap, key, val, level) log.debug('Got execution order %s for %s', level, key) dmap['create'][key]['level'] = level try: existing_list = six.iteritems(dmap['existing']) except KeyError: existing_list = six.iteritems({}) for key, val in existing_list: log.info('Calculating dependencies for %s', key) level = 0 level = self._calcdep(dmap, key, val, level) log.debug('Got execution order %s for %s', level, key) dmap['existing'][key]['level'] = level # Now sort the create list based on dependencies create_list = sorted(six.iteritems(dmap['create']), key=lambda x: x[1]['level']) full_map = dmap['create'].copy() if 'existing' in dmap: full_map.update(dmap['existing']) possible_master_list = sorted(six.iteritems(full_map), key=lambda x: x[1]['level']) output = {} if self.opts['parallel']: parallel_data = [] master_name = None master_minion_name = None master_host = None master_finger = None for name, profile in possible_master_list: if profile.get('make_master', False) is True: master_name = name master_profile = profile if master_name: # If the master already exists, get the host if master_name not in dmap['create']: master_host = self.client.query() for provider_part in master_profile['provider'].split(':'): master_host = master_host[provider_part] master_host = master_host[master_name][master_profile.get('ssh_interface', 'public_ips')] if not master_host: raise SaltCloudSystemExit( 'Could not get the hostname of master {}.'.format(master_name) ) # Otherwise, deploy it as a new master else: master_minion_name = master_name log.debug('Creating new master \'%s\'', master_name) if salt.config.get_cloud_config_value( 'deploy', master_profile, self.opts ) is False: raise SaltCloudSystemExit( 'Cannot proceed with \'make_master\' when salt deployment ' 'is disabled(ex: --no-deploy).' ) # Generate the master keys log.debug('Generating master keys for \'%s\'', master_profile['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', master_profile, self.opts ) ) master_profile['master_pub'] = pub master_profile['master_pem'] = priv # Generate the fingerprint of the master pubkey in order to # mitigate man-in-the-middle attacks master_temp_pub = salt.utils.files.mkstemp() with salt.utils.files.fopen(master_temp_pub, 'w') as mtp: mtp.write(pub) master_finger = salt.utils.crypt.pem_finger(master_temp_pub, sum_type=self.opts['hash_type']) os.unlink(master_temp_pub) if master_profile.get('make_minion', True) is True: master_profile.setdefault('minion', {}) if 'id' in master_profile['minion']: master_minion_name = master_profile['minion']['id'] # Set this minion's master as local if the user has not set it if 'master' not in master_profile['minion']: master_profile['minion']['master'] = '127.0.0.1' if master_finger is not None: master_profile['master_finger'] = master_finger # Generate the minion keys to pre-seed the master: for name, profile in create_list: make_minion = salt.config.get_cloud_config_value( 'make_minion', profile, self.opts, default=True ) if make_minion is False: continue log.debug('Generating minion keys for \'%s\'', profile['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', profile, self.opts ) ) profile['pub_key'] = pub profile['priv_key'] = priv # Store the minion's public key in order to be pre-seeded in # the master master_profile.setdefault('preseed_minion_keys', {}) master_profile['preseed_minion_keys'].update({name: pub}) local_master = False if master_profile['minion'].get('local_master', False) and \ master_profile['minion'].get('master', None) is not None: # The minion is explicitly defining a master and it's # explicitly saying it's the local one local_master = True out = self.create(master_profile, local_master=local_master) if not isinstance(out, dict): log.debug('Master creation details is not a dictionary: %s', out) elif 'Errors' in out: raise SaltCloudSystemExit( 'An error occurred while creating the master, not ' 'continuing: {0}'.format(out['Errors']) ) deploy_kwargs = ( self.opts.get('show_deploy_args', False) is True and # Get the needed data out.get('deploy_kwargs', {}) or # Strip the deploy_kwargs from the returned data since we don't # want it shown in the console. out.pop('deploy_kwargs', {}) ) master_host = deploy_kwargs.get('salt_host', deploy_kwargs.get('host', None)) if master_host is None: raise SaltCloudSystemExit( 'Host for new master {0} was not found, ' 'aborting map'.format( master_name ) ) output[master_name] = out else: log.debug('No make_master found in map') # Local master? # Generate the fingerprint of the master pubkey in order to # mitigate man-in-the-middle attacks master_pub = os.path.join(self.opts['pki_dir'], 'master.pub') if os.path.isfile(master_pub): master_finger = salt.utils.crypt.pem_finger(master_pub, sum_type=self.opts['hash_type']) opts = self.opts.copy() if self.opts['parallel']: # Force display_ssh_output to be False since the console will # need to be reset afterwards log.info( 'Since parallel deployment is in use, ssh console output ' 'is disabled. All ssh output will be logged though' ) opts['display_ssh_output'] = False local_master = master_name is None for name, profile in create_list: if name in (master_name, master_minion_name): # Already deployed, it's the master's minion continue if 'minion' in profile and profile['minion'].get('local_master', False) and \ profile['minion'].get('master', None) is not None: # The minion is explicitly defining a master and it's # explicitly saying it's the local one local_master = True if master_finger is not None and local_master is False: profile['master_finger'] = master_finger if master_host is not None: profile.setdefault('minion', {}) profile['minion'].setdefault('master', master_host) if self.opts['parallel']: parallel_data.append({ 'opts': opts, 'name': name, 'profile': profile, 'local_master': local_master }) continue # Not deploying in parallel try: output[name] = self.create( profile, local_master=local_master ) if self.opts.get('show_deploy_args', False) is False \ and 'deploy_kwargs' in output \ and isinstance(output[name], dict): output[name].pop('deploy_kwargs', None) except SaltCloudException as exc: log.error( 'Failed to deploy \'%s\'. Error: %s', name, exc, exc_info_on_loglevel=logging.DEBUG ) output[name] = {'Error': str(exc)} for name in dmap.get('destroy', ()): output[name] = self.destroy(name) if self.opts['parallel'] and parallel_data: if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Cloud pool size: %s', pool_size) output_multip = enter_mainloop( _create_multiprocessing, parallel_data, pool_size=pool_size) # We have deployed in parallel, now do start action in # correct order based on dependencies. if self.opts['start_action']: actionlist = [] grp = -1 for key, val in groupby(six.itervalues(dmap['create']), lambda x: x['level']): actionlist.append([]) grp += 1 for item in val: actionlist[grp].append(item['name']) out = {} for group in actionlist: log.info('Running %s on %s', self.opts['start_action'], ', '.join(group)) client = salt.client.get_local_client() out.update(client.cmd( ','.join(group), self.opts['start_action'], timeout=self.opts['timeout'] * 60, tgt_type='list' )) for obj in output_multip: next(six.itervalues(obj))['ret'] = out[next(six.iterkeys(obj))] output.update(obj) else: for obj in output_multip: output.update(obj) return output def init_pool_worker(): ''' Make every worker ignore KeyboarInterrup's since it will be handled by the parent process. ''' signal.signal(signal.SIGINT, signal.SIG_IGN) def create_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the create is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' cloud = Cloud(parallel_data['opts']) try: output = cloud.create( parallel_data['profile'], local_master=parallel_data['local_master'] ) except SaltCloudException as exc: log.error( 'Failed to deploy \'%s\'. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} if parallel_data['opts'].get('show_deploy_args', False) is False and isinstance(output, dict): output.pop('deploy_kwargs', None) return { parallel_data['name']: salt.utils.data.simple_types_filter(output) } def destroy_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the destroy is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' clouds = salt.loader.clouds(parallel_data['opts']) try: fun = clouds['{0}.destroy'.format(parallel_data['driver'])] with salt.utils.context.func_globals_inject( fun, __active_provider_name__=':'.join([ parallel_data['alias'], parallel_data['driver'] ]) ): output = fun(parallel_data['name']) except SaltCloudException as exc: log.error( 'Failed to destroy %s. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} return { parallel_data['name']: salt.utils.data.simple_types_filter(output) } def run_parallel_map_providers_query(data, queue=None): ''' This function will be called from another process when building the providers map. ''' salt.utils.crypt.reinit_crypto() cloud = Cloud(data['opts']) try: with salt.utils.context.func_globals_inject( cloud.clouds[data['fun']], __active_provider_name__=':'.join([ data['alias'], data['driver'] ]) ): return ( data['alias'], data['driver'], salt.utils.data.simple_types_filter( cloud.clouds[data['fun']]() ) ) except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for running nodes: %s', data['fun'], err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any nodes return data['alias'], data['driver'], () # for pickle and multiprocessing, we can't use directly decorators def _run_parallel_map_providers_query(*args, **kw): return communicator(run_parallel_map_providers_query)(*args[0], **kw) def _destroy_multiprocessing(*args, **kw): return communicator(destroy_multiprocessing)(*args[0], **kw) def _create_multiprocessing(*args, **kw): return communicator(create_multiprocessing)(*args[0], **kw)
saltstack/salt
salt/cloud/__init__.py
create_multiprocessing
python
def create_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the create is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' cloud = Cloud(parallel_data['opts']) try: output = cloud.create( parallel_data['profile'], local_master=parallel_data['local_master'] ) except SaltCloudException as exc: log.error( 'Failed to deploy \'%s\'. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} if parallel_data['opts'].get('show_deploy_args', False) is False and isinstance(output, dict): output.pop('deploy_kwargs', None) return { parallel_data['name']: salt.utils.data.simple_types_filter(output) }
This function will be called from another process when running a map in parallel mode. The result from the create is always a json object.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L2304-L2330
[ "def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n", "def reinit_crypto():\n '''\n When a fork arises, pycrypto needs to reinit\n From its doc::\n\n Caveat: For the random number generator to work correctly,\n you must call Random.atfork() in both the parent and\n child processes after using os.fork()\n\n '''\n if HAS_CRYPTO:\n Crypto.Random.atfork()\n", "def create(self, vm_, local_master=True):\n '''\n Create a single VM\n '''\n output = {}\n\n minion_dict = salt.config.get_cloud_config_value(\n 'minion', vm_, self.opts, default={}\n )\n\n alias, driver = vm_['provider'].split(':')\n fun = '{0}.create'.format(driver)\n if fun not in self.clouds:\n log.error(\n 'Creating \\'%s\\' using \\'%s\\' as the provider '\n 'cannot complete since \\'%s\\' is not available',\n vm_['name'], vm_['provider'], driver\n )\n return\n\n deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts)\n make_master = salt.config.get_cloud_config_value(\n 'make_master',\n vm_,\n self.opts\n )\n\n if deploy:\n if not make_master and 'master' not in minion_dict:\n log.warning(\n 'There\\'s no master defined on the \\'%s\\' VM settings.',\n vm_['name']\n )\n\n if 'pub_key' not in vm_ and 'priv_key' not in vm_:\n log.debug('Generating minion keys for \\'%s\\'', vm_['name'])\n priv, pub = salt.utils.cloud.gen_keys(\n salt.config.get_cloud_config_value(\n 'keysize',\n vm_,\n self.opts\n )\n )\n vm_['pub_key'] = pub\n vm_['priv_key'] = priv\n else:\n # Note(pabelanger): We still reference pub_key and priv_key when\n # deploy is disabled.\n vm_['pub_key'] = None\n vm_['priv_key'] = None\n\n key_id = minion_dict.get('id', vm_['name'])\n\n domain = vm_.get('domain')\n if vm_.get('use_fqdn') and domain:\n minion_dict['append_domain'] = domain\n\n if 'append_domain' in minion_dict:\n key_id = '.'.join([key_id, minion_dict['append_domain']])\n\n if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_:\n log.debug('Generating the master keys for \\'%s\\'', vm_['name'])\n master_priv, master_pub = salt.utils.cloud.gen_keys(\n salt.config.get_cloud_config_value(\n 'keysize',\n vm_,\n self.opts\n )\n )\n vm_['master_pub'] = master_pub\n vm_['master_pem'] = master_priv\n\n if local_master is True and deploy is True:\n # Accept the key on the local master\n salt.utils.cloud.accept_key(\n self.opts['pki_dir'], vm_['pub_key'], key_id\n )\n\n vm_['os'] = salt.config.get_cloud_config_value(\n 'script',\n vm_,\n self.opts\n )\n\n try:\n vm_['inline_script'] = salt.config.get_cloud_config_value(\n 'inline_script',\n vm_,\n self.opts\n )\n except KeyError:\n pass\n\n try:\n alias, driver = vm_['provider'].split(':')\n func = '{0}.create'.format(driver)\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=':'.join([alias, driver])\n ):\n output = self.clouds[func](vm_)\n if output is not False and 'sync_after_install' in self.opts:\n if self.opts['sync_after_install'] not in (\n 'all', 'modules', 'states', 'grains'):\n log.error('Bad option for sync_after_install')\n return output\n\n # A small pause helps the sync work more reliably\n time.sleep(3)\n\n start = int(time.time())\n while int(time.time()) < start + 60:\n # We'll try every <timeout> seconds, up to a minute\n mopts_ = salt.config.DEFAULT_MASTER_OPTS\n conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1])\n mopts_.update(\n salt.config.master_config(\n os.path.join(conf_path,\n 'master')\n )\n )\n\n client = salt.client.get_local_client(mopts=mopts_)\n\n ret = client.cmd(\n vm_['name'],\n 'saltutil.sync_{0}'.format(self.opts['sync_after_install']),\n timeout=self.opts['timeout']\n )\n if ret:\n log.info(\n six.u('Synchronized the following dynamic modules: '\n ' {0}').format(ret)\n )\n break\n except KeyError as exc:\n log.exception(\n 'Failed to create VM %s. Configuration value %s needs '\n 'to be set', vm_['name'], exc\n )\n # If it's a map then we need to respect the 'requires'\n # so we do it later\n try:\n opt_map = self.opts['map']\n except KeyError:\n opt_map = False\n if self.opts['parallel'] and self.opts['start_action'] and not opt_map:\n log.info('Running %s on %s', self.opts['start_action'], vm_['name'])\n client = salt.client.get_local_client(mopts=self.opts)\n action_out = client.cmd(\n vm_['name'],\n self.opts['start_action'],\n timeout=self.opts['timeout'] * 60\n )\n output['ret'] = action_out\n return output\n" ]
# -*- coding: utf-8 -*- ''' The top level interface used to translate configuration data back to the correct cloud modules ''' # Import python libs from __future__ import absolute_import, print_function, generators, unicode_literals import os import copy import glob import time import signal import logging import traceback import multiprocessing import sys from itertools import groupby # Import salt.cloud libs from salt.exceptions import ( SaltCloudNotFound, SaltCloudException, SaltCloudSystemExit, SaltCloudConfigError ) # Import salt libs import salt.config import salt.client import salt.loader import salt.utils.args import salt.utils.cloud import salt.utils.context import salt.utils.crypt import salt.utils.data import salt.utils.dictupdate import salt.utils.files import salt.utils.verify import salt.utils.yaml import salt.utils.user import salt.syspaths from salt.template import compile_template # Import third party libs try: import Cryptodome.Random except ImportError: try: import Crypto.Random except ImportError: pass # pycrypto < 2.1 from salt.ext import six from salt.ext.six.moves import input # pylint: disable=import-error,redefined-builtin # Get logging started log = logging.getLogger(__name__) def communicator(func): '''Warning, this is a picklable decorator !''' def _call(queue, args, kwargs): '''called with [queue, args, kwargs] as first optional arg''' kwargs['queue'] = queue ret = None try: ret = func(*args, **kwargs) queue.put('END') except KeyboardInterrupt as ex: trace = traceback.format_exc() queue.put('KEYBOARDINT') queue.put('Keyboard interrupt') queue.put('{0}\n{1}\n'.format(ex, trace)) except Exception as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('Exception') queue.put('{0}\n{1}\n'.format(ex, trace)) except SystemExit as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('System exit') queue.put('{0}\n{1}\n'.format(ex, trace)) return ret return _call def enter_mainloop(target, mapped_args=None, args=None, kwargs=None, pool=None, pool_size=None, callback=None, queue=None): ''' Manage a multiprocessing pool - If the queue does not output anything, the pool runs indefinitely - If the queue returns KEYBOARDINT or ERROR, this will kill the pool totally calling terminate & join and ands with a SaltCloudSystemExit exception notifying callers from the abnormal termination - If the queue returns END or callback is defined and returns True, it just join the process and return the data. target the function you want to execute in multiproccessing pool pool object can be None if you want a default pool, but you ll have then to define pool_size instead pool_size pool size if you did not provide yourself a pool callback a boolean taking a string in argument which returns True to signal that 'target' is finished and we need to join the pool queue A custom multiproccessing queue in case you want to do extra stuff and need it later in your program args positional arguments to call the function with if you don't want to use pool.map mapped_args a list of one or more arguments combinations to call the function with e.g. (foo, [[1], [2]]) will call:: foo([1]) foo([2]) kwargs kwargs to give to the function in case of process Attention, the function must have the following signature: target(queue, *args, **kw) You may use the 'communicator' decorator to generate such a function (see end of this file) ''' if not kwargs: kwargs = {} if not pool_size: pool_size = 1 if not pool: pool = multiprocessing.Pool(pool_size) if not queue: manager = multiprocessing.Manager() queue = manager.Queue() if mapped_args is not None and not mapped_args: msg = ( 'We are called to asynchronously execute {0}' ' but we do no have anything to execute, weird,' ' we bail out'.format(target)) log.error(msg) raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif mapped_args is not None: iterable = [[queue, [arg], kwargs] for arg in mapped_args] ret = pool.map(func=target, iterable=iterable) else: ret = pool.apply(target, [queue, args, kwargs]) while True: test = queue.get() if test in ['ERROR', 'KEYBOARDINT']: type_ = queue.get() trace = queue.get() msg = 'Caught {0}, terminating workers\n'.format(type_) msg += 'TRACE: {0}\n'.format(trace) log.error(msg) pool.terminate() pool.join() raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif test in ['END'] or (callback and callback(test)): pool.close() pool.join() break else: time.sleep(0.125) return ret class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' ) class Cloud(object): ''' An object for the creation of new VMs ''' def __init__(self, opts): self.opts = opts self.client = CloudClient(opts=self.opts) self.clouds = salt.loader.clouds(self.opts) self.__filter_non_working_providers() self.__cached_provider_queries = {} def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output def get_running_by_names(self, names, query='list_nodes', cached=False, profile=None): if isinstance(names, six.string_types): names = [names] matches = {} handled_drivers = {} mapped_providers = self.map_providers_parallel(query, cached=cached) for alias, drivers in six.iteritems(mapped_providers): for driver, vms in six.iteritems(drivers): if driver not in handled_drivers: handled_drivers[driver] = alias # When a profile is specified, only return an instance # that matches the provider specified in the profile. # This solves the issues when many providers return the # same instance. For example there may be one provider for # each availability zone in amazon in the same region, but # the search returns the same instance for each provider # because amazon returns all instances in a region, not # availability zone. if profile and alias not in self.opts['profiles'][profile]['provider'].split(':')[0]: continue for vm_name, details in six.iteritems(vms): # XXX: The logic below can be removed once the aws driver # is removed if vm_name not in names: continue elif driver == 'ec2' and 'aws' in handled_drivers and \ 'aws' in matches[handled_drivers['aws']] and \ vm_name in matches[handled_drivers['aws']]['aws']: continue elif driver == 'aws' and 'ec2' in handled_drivers and \ 'ec2' in matches[handled_drivers['ec2']] and \ vm_name in matches[handled_drivers['ec2']]['ec2']: continue if alias not in matches: matches[alias] = {} if driver not in matches[alias]: matches[alias][driver] = {} matches[alias][driver][vm_name] = details return matches def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers def location_list(self, lookup='all'): ''' Return a mapping of all location data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_locations'.format(driver) if fun not in self.clouds: # The capability to gather locations is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the locations information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def size_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_sizes'.format(driver) if fun not in self.clouds: # The capability to gather sizes is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the sizes information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output @staticmethod def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret def do_function(self, prov, func, kwargs): ''' Perform a function against a cloud provider ''' matches = self.lookup_providers(prov) if len(matches) > 1: raise SaltCloudSystemExit( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}'.format( prov, ', '.join([ '{0}:{1}'.format(alias, driver) for (alias, driver) in matches ]) ) ) alias, driver = matches.pop() fun = '{0}.{1}'.format(driver, func) if fun not in self.clouds: raise SaltCloudSystemExit( 'The \'{0}\' cloud provider alias, for the \'{1}\' driver, does ' 'not define the function \'{2}\''.format(alias, driver, func) ) log.debug( 'Trying to execute \'%s\' with the following kwargs: %s', fun, kwargs ) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if kwargs: return { alias: { driver: self.clouds[fun]( call='function', kwargs=kwargs ) } } return { alias: { driver: self.clouds[fun](call='function') } } def __filter_non_working_providers(self): ''' Remove any mis-configured cloud providers from the available listing ''' for alias, drivers in six.iteritems(self.opts['providers'].copy()): for driver in drivers.copy(): fun = '{0}.get_configured_provider'.format(driver) if fun not in self.clouds: # Mis-configured provider that got removed? log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias, could not be loaded. ' 'Please check your provider configuration files and ' 'ensure all required dependencies are installed ' 'for the \'%s\' driver.\n' 'In rare cases, this could indicate the \'%s()\' ' 'function could not be found.\nRemoving \'%s\' from ' 'the available providers list', driver, alias, driver, fun, driver ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if self.clouds[fun]() is False: log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias is not properly ' 'configured. Removing it from the available ' 'providers list.', driver, alias ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) class Map(Cloud): ''' Create a VM stateful map execution object ''' def __init__(self, opts): Cloud.__init__(self, opts) self.rendered_map = self.read() def interpolated_map(self, query='list_nodes', cached=False): rendered_map = self.read().copy() interpolated_map = {} for profile, mapped_vms in six.iteritems(rendered_map): names = set(mapped_vms) if profile not in self.opts['profiles']: if 'Errors' not in interpolated_map: interpolated_map['Errors'] = {} msg = ( 'No provider for the mapped \'{0}\' profile was found. ' 'Skipped VMS: {1}'.format( profile, ', '.join(names) ) ) log.info(msg) interpolated_map['Errors'][profile] = msg continue matching = self.get_running_by_names(names, query, cached) for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for vm_name, vm_details in six.iteritems(vms): if alias not in interpolated_map: interpolated_map[alias] = {} if driver not in interpolated_map[alias]: interpolated_map[alias][driver] = {} interpolated_map[alias][driver][vm_name] = vm_details try: names.remove(vm_name) except KeyError: # If it's not there, then our job is already done pass if not names: continue profile_details = self.opts['profiles'][profile] alias, driver = profile_details['provider'].split(':') for vm_name in names: if alias not in interpolated_map: interpolated_map[alias] = {} if driver not in interpolated_map[alias]: interpolated_map[alias][driver] = {} interpolated_map[alias][driver][vm_name] = 'Absent' return interpolated_map def delete_map(self, query=None): query_map = self.interpolated_map(query=query) for alias, drivers in six.iteritems(query_map.copy()): for driver, vms in six.iteritems(drivers.copy()): for vm_name, vm_details in six.iteritems(vms.copy()): if vm_details == 'Absent': query_map[alias][driver].pop(vm_name) if not query_map[alias][driver]: query_map[alias].pop(driver) if not query_map[alias]: query_map.pop(alias) return query_map def get_vmnames_by_action(self, action): query_map = self.interpolated_map("list_nodes") matching_states = { 'start': ['stopped'], 'stop': ['running', 'active'], 'reboot': ['running', 'active'], } vm_names = [] for alias, drivers in six.iteritems(query_map): for driver, vms in six.iteritems(drivers): for vm_name, vm_details in six.iteritems(vms): # Only certain actions are support in to use in this case. Those actions are the # "Global" salt-cloud actions defined in the "matching_states" dictionary above. # If a more specific action is passed in, we shouldn't stack-trace - exit gracefully. try: state_action = matching_states[action] except KeyError: log.error( 'The use of \'%s\' as an action is not supported ' 'in this context. Only \'start\', \'stop\', and ' '\'reboot\' are supported options.', action ) raise SaltCloudException() if vm_details != 'Absent' and vm_details['state'].lower() in state_action: vm_names.append(vm_name) return vm_names def read(self): ''' Read in the specified map and return the map structure ''' map_ = None if self.opts.get('map', None) is None: if self.opts.get('map_data', None) is None: if self.opts.get('map_pillar', None) is None: pass elif self.opts.get('map_pillar') not in self.opts.get('maps'): log.error( 'The specified map not found in pillar at ' '\'cloud:maps:%s\'', self.opts['map_pillar'] ) raise SaltCloudNotFound() else: # 'map_pillar' is provided, try to use it map_ = self.opts['maps'][self.opts.get('map_pillar')] else: # 'map_data' is provided, try to use it map_ = self.opts['map_data'] else: # 'map' is provided, try to use it local_minion_opts = copy.deepcopy(self.opts) local_minion_opts['file_client'] = 'local' self.minion = salt.minion.MasterMinion(local_minion_opts) if not os.path.isfile(self.opts['map']): if not (self.opts['map']).startswith('salt://'): log.error( 'The specified map file does not exist: \'%s\'', self.opts['map'] ) raise SaltCloudNotFound() if (self.opts['map']).startswith('salt://'): cached_map = self.minion.functions['cp.cache_file'](self.opts['map']) else: cached_map = self.opts['map'] try: renderer = self.opts.get('renderer', 'jinja|yaml') rend = salt.loader.render(self.opts, {}) blacklist = self.opts.get('renderer_blacklist') whitelist = self.opts.get('renderer_whitelist') map_ = compile_template( cached_map, rend, renderer, blacklist, whitelist ) except Exception as exc: log.error( 'Rendering map %s failed, render error:\n%s', self.opts['map'], exc, exc_info_on_loglevel=logging.DEBUG ) return {} if 'include' in map_: map_ = salt.config.include_config( map_, self.opts['map'], verbose=False ) if not map_: return {} # Create expected data format if needed for profile, mapped in six.iteritems(map_.copy()): if isinstance(mapped, (list, tuple)): entries = {} for mapping in mapped: if isinstance(mapping, six.string_types): # Foo: # - bar1 # - bar2 mapping = {mapping: None} for name, overrides in six.iteritems(mapping): if overrides is None or isinstance(overrides, bool): # Foo: # - bar1: # - bar2: overrides = {} try: overrides.setdefault('name', name) except AttributeError: log.error( 'Cannot use \'name\' as a minion id in a cloud map as it ' 'is a reserved word. Please change \'name\' to a different ' 'minion id reference.' ) return {} entries[name] = overrides map_[profile] = entries continue if isinstance(mapped, dict): # Convert the dictionary mapping to a list of dictionaries # Foo: # bar1: # grains: # foo: bar # bar2: # grains: # foo: bar entries = {} for name, overrides in six.iteritems(mapped): overrides.setdefault('name', name) entries[name] = overrides map_[profile] = entries continue if isinstance(mapped, six.string_types): # If it's a single string entry, let's make iterable because of # the next step mapped = [mapped] map_[profile] = {} for name in mapped: map_[profile][name] = {'name': name} return map_ def _has_loop(self, dmap, seen=None, val=None): if seen is None: for values in six.itervalues(dmap['create']): seen = [] try: machines = values['requires'] except KeyError: machines = [] for machine in machines: if self._has_loop(dmap, seen=list(seen), val=machine): return True else: if val in seen: return True seen.append(val) try: machines = dmap['create'][val]['requires'] except KeyError: machines = [] for machine in machines: if self._has_loop(dmap, seen=list(seen), val=machine): return True return False def _calcdep(self, dmap, machine, data, level): try: deplist = data['requires'] except KeyError: return level levels = [] for name in deplist: try: data = dmap['create'][name] except KeyError: try: data = dmap['existing'][name] except KeyError: msg = 'Missing dependency in cloud map' log.error(msg) raise SaltCloudException(msg) levels.append(self._calcdep(dmap, name, data, level)) level = max(levels) + 1 return level def map_data(self, cached=False): ''' Create a data map of what to execute on ''' ret = {'create': {}} pmap = self.map_providers_parallel(cached=cached) exist = set() defined = set() rendered_map = copy.deepcopy(self.rendered_map) for profile_name, nodes in six.iteritems(rendered_map): if profile_name not in self.opts['profiles']: msg = ( 'The required profile, \'{0}\', defined in the map ' 'does not exist. The defined nodes, {1}, will not ' 'be created.'.format( profile_name, ', '.join('\'{0}\''.format(node) for node in nodes) ) ) log.error(msg) if 'errors' not in ret: ret['errors'] = {} ret['errors'][profile_name] = msg continue profile_data = self.opts['profiles'].get(profile_name) for nodename, overrides in six.iteritems(nodes): # Get associated provider data, in case something like size # or image is specified in the provider file. See issue #32510. if 'provider' in overrides and overrides['provider'] != profile_data['provider']: alias, driver = overrides.get('provider').split(':') else: alias, driver = profile_data.get('provider').split(':') provider_details = copy.deepcopy(self.opts['providers'][alias][driver]) del provider_details['profiles'] # Update the provider details information with profile data # Profile data and node overrides should override provider data, if defined. # This keeps map file data definitions consistent with -p usage. salt.utils.dictupdate.update(provider_details, profile_data) nodedata = copy.deepcopy(provider_details) # Update profile data with the map overrides for setting in ('grains', 'master', 'minion', 'volumes', 'requires'): deprecated = 'map_{0}'.format(setting) if deprecated in overrides: log.warning( 'The use of \'%s\' on the \'%s\' mapping has ' 'been deprecated. The preferred way now is to ' 'just define \'%s\'. For now, salt-cloud will do ' 'the proper thing and convert the deprecated ' 'mapping into the preferred one.', deprecated, nodename, setting ) overrides[setting] = overrides.pop(deprecated) # merge minion grains from map file if 'minion' in overrides and \ 'minion' in nodedata and \ 'grains' in overrides['minion'] and \ 'grains' in nodedata['minion']: nodedata['minion']['grains'].update( overrides['minion']['grains'] ) del overrides['minion']['grains'] # remove minion key if now is empty dict if not overrides['minion']: del overrides['minion'] nodedata = salt.utils.dictupdate.update(nodedata, overrides) # Add the computed information to the return data ret['create'][nodename] = nodedata # Add the node name to the defined set alias, driver = nodedata['provider'].split(':') defined.add((alias, driver, nodename)) def get_matching_by_name(name): matches = {} for alias, drivers in six.iteritems(pmap): for driver, vms in six.iteritems(drivers): for vm_name, details in six.iteritems(vms): if vm_name == name and driver not in matches: matches[driver] = details['state'] return matches for alias, drivers in six.iteritems(pmap): for driver, vms in six.iteritems(drivers): for name, details in six.iteritems(vms): exist.add((alias, driver, name)) if name not in ret['create']: continue # The machine is set to be created. Does it already exist? matching = get_matching_by_name(name) if not matching: continue # A machine by the same name exists for item in matching: if name not in ret['create']: # Machine already removed break log.warning("'%s' already exists, removing from " 'the create map.', name) if 'existing' not in ret: ret['existing'] = {} ret['existing'][name] = ret['create'].pop(name) if 'hard' in self.opts and self.opts['hard']: if self.opts['enable_hard_maps'] is False: raise SaltCloudSystemExit( 'The --hard map can be extremely dangerous to use, ' 'and therefore must explicitly be enabled in the main ' 'configuration file, by setting \'enable_hard_maps\' ' 'to True' ) # Hard maps are enabled, Look for the items to delete. ret['destroy'] = exist.difference(defined) return ret def run_map(self, dmap): ''' Execute the contents of the VM map ''' if self._has_loop(dmap): msg = 'Uh-oh, that cloud map has a dependency loop!' log.error(msg) raise SaltCloudException(msg) # Go through the create list and calc dependencies for key, val in six.iteritems(dmap['create']): log.info('Calculating dependencies for %s', key) level = 0 level = self._calcdep(dmap, key, val, level) log.debug('Got execution order %s for %s', level, key) dmap['create'][key]['level'] = level try: existing_list = six.iteritems(dmap['existing']) except KeyError: existing_list = six.iteritems({}) for key, val in existing_list: log.info('Calculating dependencies for %s', key) level = 0 level = self._calcdep(dmap, key, val, level) log.debug('Got execution order %s for %s', level, key) dmap['existing'][key]['level'] = level # Now sort the create list based on dependencies create_list = sorted(six.iteritems(dmap['create']), key=lambda x: x[1]['level']) full_map = dmap['create'].copy() if 'existing' in dmap: full_map.update(dmap['existing']) possible_master_list = sorted(six.iteritems(full_map), key=lambda x: x[1]['level']) output = {} if self.opts['parallel']: parallel_data = [] master_name = None master_minion_name = None master_host = None master_finger = None for name, profile in possible_master_list: if profile.get('make_master', False) is True: master_name = name master_profile = profile if master_name: # If the master already exists, get the host if master_name not in dmap['create']: master_host = self.client.query() for provider_part in master_profile['provider'].split(':'): master_host = master_host[provider_part] master_host = master_host[master_name][master_profile.get('ssh_interface', 'public_ips')] if not master_host: raise SaltCloudSystemExit( 'Could not get the hostname of master {}.'.format(master_name) ) # Otherwise, deploy it as a new master else: master_minion_name = master_name log.debug('Creating new master \'%s\'', master_name) if salt.config.get_cloud_config_value( 'deploy', master_profile, self.opts ) is False: raise SaltCloudSystemExit( 'Cannot proceed with \'make_master\' when salt deployment ' 'is disabled(ex: --no-deploy).' ) # Generate the master keys log.debug('Generating master keys for \'%s\'', master_profile['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', master_profile, self.opts ) ) master_profile['master_pub'] = pub master_profile['master_pem'] = priv # Generate the fingerprint of the master pubkey in order to # mitigate man-in-the-middle attacks master_temp_pub = salt.utils.files.mkstemp() with salt.utils.files.fopen(master_temp_pub, 'w') as mtp: mtp.write(pub) master_finger = salt.utils.crypt.pem_finger(master_temp_pub, sum_type=self.opts['hash_type']) os.unlink(master_temp_pub) if master_profile.get('make_minion', True) is True: master_profile.setdefault('minion', {}) if 'id' in master_profile['minion']: master_minion_name = master_profile['minion']['id'] # Set this minion's master as local if the user has not set it if 'master' not in master_profile['minion']: master_profile['minion']['master'] = '127.0.0.1' if master_finger is not None: master_profile['master_finger'] = master_finger # Generate the minion keys to pre-seed the master: for name, profile in create_list: make_minion = salt.config.get_cloud_config_value( 'make_minion', profile, self.opts, default=True ) if make_minion is False: continue log.debug('Generating minion keys for \'%s\'', profile['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', profile, self.opts ) ) profile['pub_key'] = pub profile['priv_key'] = priv # Store the minion's public key in order to be pre-seeded in # the master master_profile.setdefault('preseed_minion_keys', {}) master_profile['preseed_minion_keys'].update({name: pub}) local_master = False if master_profile['minion'].get('local_master', False) and \ master_profile['minion'].get('master', None) is not None: # The minion is explicitly defining a master and it's # explicitly saying it's the local one local_master = True out = self.create(master_profile, local_master=local_master) if not isinstance(out, dict): log.debug('Master creation details is not a dictionary: %s', out) elif 'Errors' in out: raise SaltCloudSystemExit( 'An error occurred while creating the master, not ' 'continuing: {0}'.format(out['Errors']) ) deploy_kwargs = ( self.opts.get('show_deploy_args', False) is True and # Get the needed data out.get('deploy_kwargs', {}) or # Strip the deploy_kwargs from the returned data since we don't # want it shown in the console. out.pop('deploy_kwargs', {}) ) master_host = deploy_kwargs.get('salt_host', deploy_kwargs.get('host', None)) if master_host is None: raise SaltCloudSystemExit( 'Host for new master {0} was not found, ' 'aborting map'.format( master_name ) ) output[master_name] = out else: log.debug('No make_master found in map') # Local master? # Generate the fingerprint of the master pubkey in order to # mitigate man-in-the-middle attacks master_pub = os.path.join(self.opts['pki_dir'], 'master.pub') if os.path.isfile(master_pub): master_finger = salt.utils.crypt.pem_finger(master_pub, sum_type=self.opts['hash_type']) opts = self.opts.copy() if self.opts['parallel']: # Force display_ssh_output to be False since the console will # need to be reset afterwards log.info( 'Since parallel deployment is in use, ssh console output ' 'is disabled. All ssh output will be logged though' ) opts['display_ssh_output'] = False local_master = master_name is None for name, profile in create_list: if name in (master_name, master_minion_name): # Already deployed, it's the master's minion continue if 'minion' in profile and profile['minion'].get('local_master', False) and \ profile['minion'].get('master', None) is not None: # The minion is explicitly defining a master and it's # explicitly saying it's the local one local_master = True if master_finger is not None and local_master is False: profile['master_finger'] = master_finger if master_host is not None: profile.setdefault('minion', {}) profile['minion'].setdefault('master', master_host) if self.opts['parallel']: parallel_data.append({ 'opts': opts, 'name': name, 'profile': profile, 'local_master': local_master }) continue # Not deploying in parallel try: output[name] = self.create( profile, local_master=local_master ) if self.opts.get('show_deploy_args', False) is False \ and 'deploy_kwargs' in output \ and isinstance(output[name], dict): output[name].pop('deploy_kwargs', None) except SaltCloudException as exc: log.error( 'Failed to deploy \'%s\'. Error: %s', name, exc, exc_info_on_loglevel=logging.DEBUG ) output[name] = {'Error': str(exc)} for name in dmap.get('destroy', ()): output[name] = self.destroy(name) if self.opts['parallel'] and parallel_data: if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Cloud pool size: %s', pool_size) output_multip = enter_mainloop( _create_multiprocessing, parallel_data, pool_size=pool_size) # We have deployed in parallel, now do start action in # correct order based on dependencies. if self.opts['start_action']: actionlist = [] grp = -1 for key, val in groupby(six.itervalues(dmap['create']), lambda x: x['level']): actionlist.append([]) grp += 1 for item in val: actionlist[grp].append(item['name']) out = {} for group in actionlist: log.info('Running %s on %s', self.opts['start_action'], ', '.join(group)) client = salt.client.get_local_client() out.update(client.cmd( ','.join(group), self.opts['start_action'], timeout=self.opts['timeout'] * 60, tgt_type='list' )) for obj in output_multip: next(six.itervalues(obj))['ret'] = out[next(six.iterkeys(obj))] output.update(obj) else: for obj in output_multip: output.update(obj) return output def init_pool_worker(): ''' Make every worker ignore KeyboarInterrup's since it will be handled by the parent process. ''' signal.signal(signal.SIGINT, signal.SIG_IGN) def destroy_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the destroy is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' clouds = salt.loader.clouds(parallel_data['opts']) try: fun = clouds['{0}.destroy'.format(parallel_data['driver'])] with salt.utils.context.func_globals_inject( fun, __active_provider_name__=':'.join([ parallel_data['alias'], parallel_data['driver'] ]) ): output = fun(parallel_data['name']) except SaltCloudException as exc: log.error( 'Failed to destroy %s. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} return { parallel_data['name']: salt.utils.data.simple_types_filter(output) } def run_parallel_map_providers_query(data, queue=None): ''' This function will be called from another process when building the providers map. ''' salt.utils.crypt.reinit_crypto() cloud = Cloud(data['opts']) try: with salt.utils.context.func_globals_inject( cloud.clouds[data['fun']], __active_provider_name__=':'.join([ data['alias'], data['driver'] ]) ): return ( data['alias'], data['driver'], salt.utils.data.simple_types_filter( cloud.clouds[data['fun']]() ) ) except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for running nodes: %s', data['fun'], err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any nodes return data['alias'], data['driver'], () # for pickle and multiprocessing, we can't use directly decorators def _run_parallel_map_providers_query(*args, **kw): return communicator(run_parallel_map_providers_query)(*args[0], **kw) def _destroy_multiprocessing(*args, **kw): return communicator(destroy_multiprocessing)(*args[0], **kw) def _create_multiprocessing(*args, **kw): return communicator(create_multiprocessing)(*args[0], **kw)
saltstack/salt
salt/cloud/__init__.py
destroy_multiprocessing
python
def destroy_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the destroy is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' clouds = salt.loader.clouds(parallel_data['opts']) try: fun = clouds['{0}.destroy'.format(parallel_data['driver'])] with salt.utils.context.func_globals_inject( fun, __active_provider_name__=':'.join([ parallel_data['alias'], parallel_data['driver'] ]) ): output = fun(parallel_data['name']) except SaltCloudException as exc: log.error( 'Failed to destroy %s. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} return { parallel_data['name']: salt.utils.data.simple_types_filter(output) }
This function will be called from another process when running a map in parallel mode. The result from the destroy is always a json object.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L2333-L2363
[ "def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n", "def reinit_crypto():\n '''\n When a fork arises, pycrypto needs to reinit\n From its doc::\n\n Caveat: For the random number generator to work correctly,\n you must call Random.atfork() in both the parent and\n child processes after using os.fork()\n\n '''\n if HAS_CRYPTO:\n Crypto.Random.atfork()\n" ]
# -*- coding: utf-8 -*- ''' The top level interface used to translate configuration data back to the correct cloud modules ''' # Import python libs from __future__ import absolute_import, print_function, generators, unicode_literals import os import copy import glob import time import signal import logging import traceback import multiprocessing import sys from itertools import groupby # Import salt.cloud libs from salt.exceptions import ( SaltCloudNotFound, SaltCloudException, SaltCloudSystemExit, SaltCloudConfigError ) # Import salt libs import salt.config import salt.client import salt.loader import salt.utils.args import salt.utils.cloud import salt.utils.context import salt.utils.crypt import salt.utils.data import salt.utils.dictupdate import salt.utils.files import salt.utils.verify import salt.utils.yaml import salt.utils.user import salt.syspaths from salt.template import compile_template # Import third party libs try: import Cryptodome.Random except ImportError: try: import Crypto.Random except ImportError: pass # pycrypto < 2.1 from salt.ext import six from salt.ext.six.moves import input # pylint: disable=import-error,redefined-builtin # Get logging started log = logging.getLogger(__name__) def communicator(func): '''Warning, this is a picklable decorator !''' def _call(queue, args, kwargs): '''called with [queue, args, kwargs] as first optional arg''' kwargs['queue'] = queue ret = None try: ret = func(*args, **kwargs) queue.put('END') except KeyboardInterrupt as ex: trace = traceback.format_exc() queue.put('KEYBOARDINT') queue.put('Keyboard interrupt') queue.put('{0}\n{1}\n'.format(ex, trace)) except Exception as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('Exception') queue.put('{0}\n{1}\n'.format(ex, trace)) except SystemExit as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('System exit') queue.put('{0}\n{1}\n'.format(ex, trace)) return ret return _call def enter_mainloop(target, mapped_args=None, args=None, kwargs=None, pool=None, pool_size=None, callback=None, queue=None): ''' Manage a multiprocessing pool - If the queue does not output anything, the pool runs indefinitely - If the queue returns KEYBOARDINT or ERROR, this will kill the pool totally calling terminate & join and ands with a SaltCloudSystemExit exception notifying callers from the abnormal termination - If the queue returns END or callback is defined and returns True, it just join the process and return the data. target the function you want to execute in multiproccessing pool pool object can be None if you want a default pool, but you ll have then to define pool_size instead pool_size pool size if you did not provide yourself a pool callback a boolean taking a string in argument which returns True to signal that 'target' is finished and we need to join the pool queue A custom multiproccessing queue in case you want to do extra stuff and need it later in your program args positional arguments to call the function with if you don't want to use pool.map mapped_args a list of one or more arguments combinations to call the function with e.g. (foo, [[1], [2]]) will call:: foo([1]) foo([2]) kwargs kwargs to give to the function in case of process Attention, the function must have the following signature: target(queue, *args, **kw) You may use the 'communicator' decorator to generate such a function (see end of this file) ''' if not kwargs: kwargs = {} if not pool_size: pool_size = 1 if not pool: pool = multiprocessing.Pool(pool_size) if not queue: manager = multiprocessing.Manager() queue = manager.Queue() if mapped_args is not None and not mapped_args: msg = ( 'We are called to asynchronously execute {0}' ' but we do no have anything to execute, weird,' ' we bail out'.format(target)) log.error(msg) raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif mapped_args is not None: iterable = [[queue, [arg], kwargs] for arg in mapped_args] ret = pool.map(func=target, iterable=iterable) else: ret = pool.apply(target, [queue, args, kwargs]) while True: test = queue.get() if test in ['ERROR', 'KEYBOARDINT']: type_ = queue.get() trace = queue.get() msg = 'Caught {0}, terminating workers\n'.format(type_) msg += 'TRACE: {0}\n'.format(trace) log.error(msg) pool.terminate() pool.join() raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif test in ['END'] or (callback and callback(test)): pool.close() pool.join() break else: time.sleep(0.125) return ret class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' ) class Cloud(object): ''' An object for the creation of new VMs ''' def __init__(self, opts): self.opts = opts self.client = CloudClient(opts=self.opts) self.clouds = salt.loader.clouds(self.opts) self.__filter_non_working_providers() self.__cached_provider_queries = {} def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output def get_running_by_names(self, names, query='list_nodes', cached=False, profile=None): if isinstance(names, six.string_types): names = [names] matches = {} handled_drivers = {} mapped_providers = self.map_providers_parallel(query, cached=cached) for alias, drivers in six.iteritems(mapped_providers): for driver, vms in six.iteritems(drivers): if driver not in handled_drivers: handled_drivers[driver] = alias # When a profile is specified, only return an instance # that matches the provider specified in the profile. # This solves the issues when many providers return the # same instance. For example there may be one provider for # each availability zone in amazon in the same region, but # the search returns the same instance for each provider # because amazon returns all instances in a region, not # availability zone. if profile and alias not in self.opts['profiles'][profile]['provider'].split(':')[0]: continue for vm_name, details in six.iteritems(vms): # XXX: The logic below can be removed once the aws driver # is removed if vm_name not in names: continue elif driver == 'ec2' and 'aws' in handled_drivers and \ 'aws' in matches[handled_drivers['aws']] and \ vm_name in matches[handled_drivers['aws']]['aws']: continue elif driver == 'aws' and 'ec2' in handled_drivers and \ 'ec2' in matches[handled_drivers['ec2']] and \ vm_name in matches[handled_drivers['ec2']]['ec2']: continue if alias not in matches: matches[alias] = {} if driver not in matches[alias]: matches[alias][driver] = {} matches[alias][driver][vm_name] = details return matches def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers def location_list(self, lookup='all'): ''' Return a mapping of all location data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_locations'.format(driver) if fun not in self.clouds: # The capability to gather locations is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the locations information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def size_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_sizes'.format(driver) if fun not in self.clouds: # The capability to gather sizes is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the sizes information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output @staticmethod def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret def do_function(self, prov, func, kwargs): ''' Perform a function against a cloud provider ''' matches = self.lookup_providers(prov) if len(matches) > 1: raise SaltCloudSystemExit( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}'.format( prov, ', '.join([ '{0}:{1}'.format(alias, driver) for (alias, driver) in matches ]) ) ) alias, driver = matches.pop() fun = '{0}.{1}'.format(driver, func) if fun not in self.clouds: raise SaltCloudSystemExit( 'The \'{0}\' cloud provider alias, for the \'{1}\' driver, does ' 'not define the function \'{2}\''.format(alias, driver, func) ) log.debug( 'Trying to execute \'%s\' with the following kwargs: %s', fun, kwargs ) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if kwargs: return { alias: { driver: self.clouds[fun]( call='function', kwargs=kwargs ) } } return { alias: { driver: self.clouds[fun](call='function') } } def __filter_non_working_providers(self): ''' Remove any mis-configured cloud providers from the available listing ''' for alias, drivers in six.iteritems(self.opts['providers'].copy()): for driver in drivers.copy(): fun = '{0}.get_configured_provider'.format(driver) if fun not in self.clouds: # Mis-configured provider that got removed? log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias, could not be loaded. ' 'Please check your provider configuration files and ' 'ensure all required dependencies are installed ' 'for the \'%s\' driver.\n' 'In rare cases, this could indicate the \'%s()\' ' 'function could not be found.\nRemoving \'%s\' from ' 'the available providers list', driver, alias, driver, fun, driver ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if self.clouds[fun]() is False: log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias is not properly ' 'configured. Removing it from the available ' 'providers list.', driver, alias ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) class Map(Cloud): ''' Create a VM stateful map execution object ''' def __init__(self, opts): Cloud.__init__(self, opts) self.rendered_map = self.read() def interpolated_map(self, query='list_nodes', cached=False): rendered_map = self.read().copy() interpolated_map = {} for profile, mapped_vms in six.iteritems(rendered_map): names = set(mapped_vms) if profile not in self.opts['profiles']: if 'Errors' not in interpolated_map: interpolated_map['Errors'] = {} msg = ( 'No provider for the mapped \'{0}\' profile was found. ' 'Skipped VMS: {1}'.format( profile, ', '.join(names) ) ) log.info(msg) interpolated_map['Errors'][profile] = msg continue matching = self.get_running_by_names(names, query, cached) for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for vm_name, vm_details in six.iteritems(vms): if alias not in interpolated_map: interpolated_map[alias] = {} if driver not in interpolated_map[alias]: interpolated_map[alias][driver] = {} interpolated_map[alias][driver][vm_name] = vm_details try: names.remove(vm_name) except KeyError: # If it's not there, then our job is already done pass if not names: continue profile_details = self.opts['profiles'][profile] alias, driver = profile_details['provider'].split(':') for vm_name in names: if alias not in interpolated_map: interpolated_map[alias] = {} if driver not in interpolated_map[alias]: interpolated_map[alias][driver] = {} interpolated_map[alias][driver][vm_name] = 'Absent' return interpolated_map def delete_map(self, query=None): query_map = self.interpolated_map(query=query) for alias, drivers in six.iteritems(query_map.copy()): for driver, vms in six.iteritems(drivers.copy()): for vm_name, vm_details in six.iteritems(vms.copy()): if vm_details == 'Absent': query_map[alias][driver].pop(vm_name) if not query_map[alias][driver]: query_map[alias].pop(driver) if not query_map[alias]: query_map.pop(alias) return query_map def get_vmnames_by_action(self, action): query_map = self.interpolated_map("list_nodes") matching_states = { 'start': ['stopped'], 'stop': ['running', 'active'], 'reboot': ['running', 'active'], } vm_names = [] for alias, drivers in six.iteritems(query_map): for driver, vms in six.iteritems(drivers): for vm_name, vm_details in six.iteritems(vms): # Only certain actions are support in to use in this case. Those actions are the # "Global" salt-cloud actions defined in the "matching_states" dictionary above. # If a more specific action is passed in, we shouldn't stack-trace - exit gracefully. try: state_action = matching_states[action] except KeyError: log.error( 'The use of \'%s\' as an action is not supported ' 'in this context. Only \'start\', \'stop\', and ' '\'reboot\' are supported options.', action ) raise SaltCloudException() if vm_details != 'Absent' and vm_details['state'].lower() in state_action: vm_names.append(vm_name) return vm_names def read(self): ''' Read in the specified map and return the map structure ''' map_ = None if self.opts.get('map', None) is None: if self.opts.get('map_data', None) is None: if self.opts.get('map_pillar', None) is None: pass elif self.opts.get('map_pillar') not in self.opts.get('maps'): log.error( 'The specified map not found in pillar at ' '\'cloud:maps:%s\'', self.opts['map_pillar'] ) raise SaltCloudNotFound() else: # 'map_pillar' is provided, try to use it map_ = self.opts['maps'][self.opts.get('map_pillar')] else: # 'map_data' is provided, try to use it map_ = self.opts['map_data'] else: # 'map' is provided, try to use it local_minion_opts = copy.deepcopy(self.opts) local_minion_opts['file_client'] = 'local' self.minion = salt.minion.MasterMinion(local_minion_opts) if not os.path.isfile(self.opts['map']): if not (self.opts['map']).startswith('salt://'): log.error( 'The specified map file does not exist: \'%s\'', self.opts['map'] ) raise SaltCloudNotFound() if (self.opts['map']).startswith('salt://'): cached_map = self.minion.functions['cp.cache_file'](self.opts['map']) else: cached_map = self.opts['map'] try: renderer = self.opts.get('renderer', 'jinja|yaml') rend = salt.loader.render(self.opts, {}) blacklist = self.opts.get('renderer_blacklist') whitelist = self.opts.get('renderer_whitelist') map_ = compile_template( cached_map, rend, renderer, blacklist, whitelist ) except Exception as exc: log.error( 'Rendering map %s failed, render error:\n%s', self.opts['map'], exc, exc_info_on_loglevel=logging.DEBUG ) return {} if 'include' in map_: map_ = salt.config.include_config( map_, self.opts['map'], verbose=False ) if not map_: return {} # Create expected data format if needed for profile, mapped in six.iteritems(map_.copy()): if isinstance(mapped, (list, tuple)): entries = {} for mapping in mapped: if isinstance(mapping, six.string_types): # Foo: # - bar1 # - bar2 mapping = {mapping: None} for name, overrides in six.iteritems(mapping): if overrides is None or isinstance(overrides, bool): # Foo: # - bar1: # - bar2: overrides = {} try: overrides.setdefault('name', name) except AttributeError: log.error( 'Cannot use \'name\' as a minion id in a cloud map as it ' 'is a reserved word. Please change \'name\' to a different ' 'minion id reference.' ) return {} entries[name] = overrides map_[profile] = entries continue if isinstance(mapped, dict): # Convert the dictionary mapping to a list of dictionaries # Foo: # bar1: # grains: # foo: bar # bar2: # grains: # foo: bar entries = {} for name, overrides in six.iteritems(mapped): overrides.setdefault('name', name) entries[name] = overrides map_[profile] = entries continue if isinstance(mapped, six.string_types): # If it's a single string entry, let's make iterable because of # the next step mapped = [mapped] map_[profile] = {} for name in mapped: map_[profile][name] = {'name': name} return map_ def _has_loop(self, dmap, seen=None, val=None): if seen is None: for values in six.itervalues(dmap['create']): seen = [] try: machines = values['requires'] except KeyError: machines = [] for machine in machines: if self._has_loop(dmap, seen=list(seen), val=machine): return True else: if val in seen: return True seen.append(val) try: machines = dmap['create'][val]['requires'] except KeyError: machines = [] for machine in machines: if self._has_loop(dmap, seen=list(seen), val=machine): return True return False def _calcdep(self, dmap, machine, data, level): try: deplist = data['requires'] except KeyError: return level levels = [] for name in deplist: try: data = dmap['create'][name] except KeyError: try: data = dmap['existing'][name] except KeyError: msg = 'Missing dependency in cloud map' log.error(msg) raise SaltCloudException(msg) levels.append(self._calcdep(dmap, name, data, level)) level = max(levels) + 1 return level def map_data(self, cached=False): ''' Create a data map of what to execute on ''' ret = {'create': {}} pmap = self.map_providers_parallel(cached=cached) exist = set() defined = set() rendered_map = copy.deepcopy(self.rendered_map) for profile_name, nodes in six.iteritems(rendered_map): if profile_name not in self.opts['profiles']: msg = ( 'The required profile, \'{0}\', defined in the map ' 'does not exist. The defined nodes, {1}, will not ' 'be created.'.format( profile_name, ', '.join('\'{0}\''.format(node) for node in nodes) ) ) log.error(msg) if 'errors' not in ret: ret['errors'] = {} ret['errors'][profile_name] = msg continue profile_data = self.opts['profiles'].get(profile_name) for nodename, overrides in six.iteritems(nodes): # Get associated provider data, in case something like size # or image is specified in the provider file. See issue #32510. if 'provider' in overrides and overrides['provider'] != profile_data['provider']: alias, driver = overrides.get('provider').split(':') else: alias, driver = profile_data.get('provider').split(':') provider_details = copy.deepcopy(self.opts['providers'][alias][driver]) del provider_details['profiles'] # Update the provider details information with profile data # Profile data and node overrides should override provider data, if defined. # This keeps map file data definitions consistent with -p usage. salt.utils.dictupdate.update(provider_details, profile_data) nodedata = copy.deepcopy(provider_details) # Update profile data with the map overrides for setting in ('grains', 'master', 'minion', 'volumes', 'requires'): deprecated = 'map_{0}'.format(setting) if deprecated in overrides: log.warning( 'The use of \'%s\' on the \'%s\' mapping has ' 'been deprecated. The preferred way now is to ' 'just define \'%s\'. For now, salt-cloud will do ' 'the proper thing and convert the deprecated ' 'mapping into the preferred one.', deprecated, nodename, setting ) overrides[setting] = overrides.pop(deprecated) # merge minion grains from map file if 'minion' in overrides and \ 'minion' in nodedata and \ 'grains' in overrides['minion'] and \ 'grains' in nodedata['minion']: nodedata['minion']['grains'].update( overrides['minion']['grains'] ) del overrides['minion']['grains'] # remove minion key if now is empty dict if not overrides['minion']: del overrides['minion'] nodedata = salt.utils.dictupdate.update(nodedata, overrides) # Add the computed information to the return data ret['create'][nodename] = nodedata # Add the node name to the defined set alias, driver = nodedata['provider'].split(':') defined.add((alias, driver, nodename)) def get_matching_by_name(name): matches = {} for alias, drivers in six.iteritems(pmap): for driver, vms in six.iteritems(drivers): for vm_name, details in six.iteritems(vms): if vm_name == name and driver not in matches: matches[driver] = details['state'] return matches for alias, drivers in six.iteritems(pmap): for driver, vms in six.iteritems(drivers): for name, details in six.iteritems(vms): exist.add((alias, driver, name)) if name not in ret['create']: continue # The machine is set to be created. Does it already exist? matching = get_matching_by_name(name) if not matching: continue # A machine by the same name exists for item in matching: if name not in ret['create']: # Machine already removed break log.warning("'%s' already exists, removing from " 'the create map.', name) if 'existing' not in ret: ret['existing'] = {} ret['existing'][name] = ret['create'].pop(name) if 'hard' in self.opts and self.opts['hard']: if self.opts['enable_hard_maps'] is False: raise SaltCloudSystemExit( 'The --hard map can be extremely dangerous to use, ' 'and therefore must explicitly be enabled in the main ' 'configuration file, by setting \'enable_hard_maps\' ' 'to True' ) # Hard maps are enabled, Look for the items to delete. ret['destroy'] = exist.difference(defined) return ret def run_map(self, dmap): ''' Execute the contents of the VM map ''' if self._has_loop(dmap): msg = 'Uh-oh, that cloud map has a dependency loop!' log.error(msg) raise SaltCloudException(msg) # Go through the create list and calc dependencies for key, val in six.iteritems(dmap['create']): log.info('Calculating dependencies for %s', key) level = 0 level = self._calcdep(dmap, key, val, level) log.debug('Got execution order %s for %s', level, key) dmap['create'][key]['level'] = level try: existing_list = six.iteritems(dmap['existing']) except KeyError: existing_list = six.iteritems({}) for key, val in existing_list: log.info('Calculating dependencies for %s', key) level = 0 level = self._calcdep(dmap, key, val, level) log.debug('Got execution order %s for %s', level, key) dmap['existing'][key]['level'] = level # Now sort the create list based on dependencies create_list = sorted(six.iteritems(dmap['create']), key=lambda x: x[1]['level']) full_map = dmap['create'].copy() if 'existing' in dmap: full_map.update(dmap['existing']) possible_master_list = sorted(six.iteritems(full_map), key=lambda x: x[1]['level']) output = {} if self.opts['parallel']: parallel_data = [] master_name = None master_minion_name = None master_host = None master_finger = None for name, profile in possible_master_list: if profile.get('make_master', False) is True: master_name = name master_profile = profile if master_name: # If the master already exists, get the host if master_name not in dmap['create']: master_host = self.client.query() for provider_part in master_profile['provider'].split(':'): master_host = master_host[provider_part] master_host = master_host[master_name][master_profile.get('ssh_interface', 'public_ips')] if not master_host: raise SaltCloudSystemExit( 'Could not get the hostname of master {}.'.format(master_name) ) # Otherwise, deploy it as a new master else: master_minion_name = master_name log.debug('Creating new master \'%s\'', master_name) if salt.config.get_cloud_config_value( 'deploy', master_profile, self.opts ) is False: raise SaltCloudSystemExit( 'Cannot proceed with \'make_master\' when salt deployment ' 'is disabled(ex: --no-deploy).' ) # Generate the master keys log.debug('Generating master keys for \'%s\'', master_profile['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', master_profile, self.opts ) ) master_profile['master_pub'] = pub master_profile['master_pem'] = priv # Generate the fingerprint of the master pubkey in order to # mitigate man-in-the-middle attacks master_temp_pub = salt.utils.files.mkstemp() with salt.utils.files.fopen(master_temp_pub, 'w') as mtp: mtp.write(pub) master_finger = salt.utils.crypt.pem_finger(master_temp_pub, sum_type=self.opts['hash_type']) os.unlink(master_temp_pub) if master_profile.get('make_minion', True) is True: master_profile.setdefault('minion', {}) if 'id' in master_profile['minion']: master_minion_name = master_profile['minion']['id'] # Set this minion's master as local if the user has not set it if 'master' not in master_profile['minion']: master_profile['minion']['master'] = '127.0.0.1' if master_finger is not None: master_profile['master_finger'] = master_finger # Generate the minion keys to pre-seed the master: for name, profile in create_list: make_minion = salt.config.get_cloud_config_value( 'make_minion', profile, self.opts, default=True ) if make_minion is False: continue log.debug('Generating minion keys for \'%s\'', profile['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', profile, self.opts ) ) profile['pub_key'] = pub profile['priv_key'] = priv # Store the minion's public key in order to be pre-seeded in # the master master_profile.setdefault('preseed_minion_keys', {}) master_profile['preseed_minion_keys'].update({name: pub}) local_master = False if master_profile['minion'].get('local_master', False) and \ master_profile['minion'].get('master', None) is not None: # The minion is explicitly defining a master and it's # explicitly saying it's the local one local_master = True out = self.create(master_profile, local_master=local_master) if not isinstance(out, dict): log.debug('Master creation details is not a dictionary: %s', out) elif 'Errors' in out: raise SaltCloudSystemExit( 'An error occurred while creating the master, not ' 'continuing: {0}'.format(out['Errors']) ) deploy_kwargs = ( self.opts.get('show_deploy_args', False) is True and # Get the needed data out.get('deploy_kwargs', {}) or # Strip the deploy_kwargs from the returned data since we don't # want it shown in the console. out.pop('deploy_kwargs', {}) ) master_host = deploy_kwargs.get('salt_host', deploy_kwargs.get('host', None)) if master_host is None: raise SaltCloudSystemExit( 'Host for new master {0} was not found, ' 'aborting map'.format( master_name ) ) output[master_name] = out else: log.debug('No make_master found in map') # Local master? # Generate the fingerprint of the master pubkey in order to # mitigate man-in-the-middle attacks master_pub = os.path.join(self.opts['pki_dir'], 'master.pub') if os.path.isfile(master_pub): master_finger = salt.utils.crypt.pem_finger(master_pub, sum_type=self.opts['hash_type']) opts = self.opts.copy() if self.opts['parallel']: # Force display_ssh_output to be False since the console will # need to be reset afterwards log.info( 'Since parallel deployment is in use, ssh console output ' 'is disabled. All ssh output will be logged though' ) opts['display_ssh_output'] = False local_master = master_name is None for name, profile in create_list: if name in (master_name, master_minion_name): # Already deployed, it's the master's minion continue if 'minion' in profile and profile['minion'].get('local_master', False) and \ profile['minion'].get('master', None) is not None: # The minion is explicitly defining a master and it's # explicitly saying it's the local one local_master = True if master_finger is not None and local_master is False: profile['master_finger'] = master_finger if master_host is not None: profile.setdefault('minion', {}) profile['minion'].setdefault('master', master_host) if self.opts['parallel']: parallel_data.append({ 'opts': opts, 'name': name, 'profile': profile, 'local_master': local_master }) continue # Not deploying in parallel try: output[name] = self.create( profile, local_master=local_master ) if self.opts.get('show_deploy_args', False) is False \ and 'deploy_kwargs' in output \ and isinstance(output[name], dict): output[name].pop('deploy_kwargs', None) except SaltCloudException as exc: log.error( 'Failed to deploy \'%s\'. Error: %s', name, exc, exc_info_on_loglevel=logging.DEBUG ) output[name] = {'Error': str(exc)} for name in dmap.get('destroy', ()): output[name] = self.destroy(name) if self.opts['parallel'] and parallel_data: if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Cloud pool size: %s', pool_size) output_multip = enter_mainloop( _create_multiprocessing, parallel_data, pool_size=pool_size) # We have deployed in parallel, now do start action in # correct order based on dependencies. if self.opts['start_action']: actionlist = [] grp = -1 for key, val in groupby(six.itervalues(dmap['create']), lambda x: x['level']): actionlist.append([]) grp += 1 for item in val: actionlist[grp].append(item['name']) out = {} for group in actionlist: log.info('Running %s on %s', self.opts['start_action'], ', '.join(group)) client = salt.client.get_local_client() out.update(client.cmd( ','.join(group), self.opts['start_action'], timeout=self.opts['timeout'] * 60, tgt_type='list' )) for obj in output_multip: next(six.itervalues(obj))['ret'] = out[next(six.iterkeys(obj))] output.update(obj) else: for obj in output_multip: output.update(obj) return output def init_pool_worker(): ''' Make every worker ignore KeyboarInterrup's since it will be handled by the parent process. ''' signal.signal(signal.SIGINT, signal.SIG_IGN) def create_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the create is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' cloud = Cloud(parallel_data['opts']) try: output = cloud.create( parallel_data['profile'], local_master=parallel_data['local_master'] ) except SaltCloudException as exc: log.error( 'Failed to deploy \'%s\'. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} if parallel_data['opts'].get('show_deploy_args', False) is False and isinstance(output, dict): output.pop('deploy_kwargs', None) return { parallel_data['name']: salt.utils.data.simple_types_filter(output) } def run_parallel_map_providers_query(data, queue=None): ''' This function will be called from another process when building the providers map. ''' salt.utils.crypt.reinit_crypto() cloud = Cloud(data['opts']) try: with salt.utils.context.func_globals_inject( cloud.clouds[data['fun']], __active_provider_name__=':'.join([ data['alias'], data['driver'] ]) ): return ( data['alias'], data['driver'], salt.utils.data.simple_types_filter( cloud.clouds[data['fun']]() ) ) except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for running nodes: %s', data['fun'], err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any nodes return data['alias'], data['driver'], () # for pickle and multiprocessing, we can't use directly decorators def _run_parallel_map_providers_query(*args, **kw): return communicator(run_parallel_map_providers_query)(*args[0], **kw) def _destroy_multiprocessing(*args, **kw): return communicator(destroy_multiprocessing)(*args[0], **kw) def _create_multiprocessing(*args, **kw): return communicator(create_multiprocessing)(*args[0], **kw)
saltstack/salt
salt/cloud/__init__.py
run_parallel_map_providers_query
python
def run_parallel_map_providers_query(data, queue=None): ''' This function will be called from another process when building the providers map. ''' salt.utils.crypt.reinit_crypto() cloud = Cloud(data['opts']) try: with salt.utils.context.func_globals_inject( cloud.clouds[data['fun']], __active_provider_name__=':'.join([ data['alias'], data['driver'] ]) ): return ( data['alias'], data['driver'], salt.utils.data.simple_types_filter( cloud.clouds[data['fun']]() ) ) except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for running nodes: %s', data['fun'], err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any nodes return data['alias'], data['driver'], ()
This function will be called from another process when building the providers map.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L2366-L2395
[ "def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n", "def reinit_crypto():\n '''\n When a fork arises, pycrypto needs to reinit\n From its doc::\n\n Caveat: For the random number generator to work correctly,\n you must call Random.atfork() in both the parent and\n child processes after using os.fork()\n\n '''\n if HAS_CRYPTO:\n Crypto.Random.atfork()\n" ]
# -*- coding: utf-8 -*- ''' The top level interface used to translate configuration data back to the correct cloud modules ''' # Import python libs from __future__ import absolute_import, print_function, generators, unicode_literals import os import copy import glob import time import signal import logging import traceback import multiprocessing import sys from itertools import groupby # Import salt.cloud libs from salt.exceptions import ( SaltCloudNotFound, SaltCloudException, SaltCloudSystemExit, SaltCloudConfigError ) # Import salt libs import salt.config import salt.client import salt.loader import salt.utils.args import salt.utils.cloud import salt.utils.context import salt.utils.crypt import salt.utils.data import salt.utils.dictupdate import salt.utils.files import salt.utils.verify import salt.utils.yaml import salt.utils.user import salt.syspaths from salt.template import compile_template # Import third party libs try: import Cryptodome.Random except ImportError: try: import Crypto.Random except ImportError: pass # pycrypto < 2.1 from salt.ext import six from salt.ext.six.moves import input # pylint: disable=import-error,redefined-builtin # Get logging started log = logging.getLogger(__name__) def communicator(func): '''Warning, this is a picklable decorator !''' def _call(queue, args, kwargs): '''called with [queue, args, kwargs] as first optional arg''' kwargs['queue'] = queue ret = None try: ret = func(*args, **kwargs) queue.put('END') except KeyboardInterrupt as ex: trace = traceback.format_exc() queue.put('KEYBOARDINT') queue.put('Keyboard interrupt') queue.put('{0}\n{1}\n'.format(ex, trace)) except Exception as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('Exception') queue.put('{0}\n{1}\n'.format(ex, trace)) except SystemExit as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('System exit') queue.put('{0}\n{1}\n'.format(ex, trace)) return ret return _call def enter_mainloop(target, mapped_args=None, args=None, kwargs=None, pool=None, pool_size=None, callback=None, queue=None): ''' Manage a multiprocessing pool - If the queue does not output anything, the pool runs indefinitely - If the queue returns KEYBOARDINT or ERROR, this will kill the pool totally calling terminate & join and ands with a SaltCloudSystemExit exception notifying callers from the abnormal termination - If the queue returns END or callback is defined and returns True, it just join the process and return the data. target the function you want to execute in multiproccessing pool pool object can be None if you want a default pool, but you ll have then to define pool_size instead pool_size pool size if you did not provide yourself a pool callback a boolean taking a string in argument which returns True to signal that 'target' is finished and we need to join the pool queue A custom multiproccessing queue in case you want to do extra stuff and need it later in your program args positional arguments to call the function with if you don't want to use pool.map mapped_args a list of one or more arguments combinations to call the function with e.g. (foo, [[1], [2]]) will call:: foo([1]) foo([2]) kwargs kwargs to give to the function in case of process Attention, the function must have the following signature: target(queue, *args, **kw) You may use the 'communicator' decorator to generate such a function (see end of this file) ''' if not kwargs: kwargs = {} if not pool_size: pool_size = 1 if not pool: pool = multiprocessing.Pool(pool_size) if not queue: manager = multiprocessing.Manager() queue = manager.Queue() if mapped_args is not None and not mapped_args: msg = ( 'We are called to asynchronously execute {0}' ' but we do no have anything to execute, weird,' ' we bail out'.format(target)) log.error(msg) raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif mapped_args is not None: iterable = [[queue, [arg], kwargs] for arg in mapped_args] ret = pool.map(func=target, iterable=iterable) else: ret = pool.apply(target, [queue, args, kwargs]) while True: test = queue.get() if test in ['ERROR', 'KEYBOARDINT']: type_ = queue.get() trace = queue.get() msg = 'Caught {0}, terminating workers\n'.format(type_) msg += 'TRACE: {0}\n'.format(trace) log.error(msg) pool.terminate() pool.join() raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif test in ['END'] or (callback and callback(test)): pool.close() pool.join() break else: time.sleep(0.125) return ret class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' ) class Cloud(object): ''' An object for the creation of new VMs ''' def __init__(self, opts): self.opts = opts self.client = CloudClient(opts=self.opts) self.clouds = salt.loader.clouds(self.opts) self.__filter_non_working_providers() self.__cached_provider_queries = {} def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output def get_running_by_names(self, names, query='list_nodes', cached=False, profile=None): if isinstance(names, six.string_types): names = [names] matches = {} handled_drivers = {} mapped_providers = self.map_providers_parallel(query, cached=cached) for alias, drivers in six.iteritems(mapped_providers): for driver, vms in six.iteritems(drivers): if driver not in handled_drivers: handled_drivers[driver] = alias # When a profile is specified, only return an instance # that matches the provider specified in the profile. # This solves the issues when many providers return the # same instance. For example there may be one provider for # each availability zone in amazon in the same region, but # the search returns the same instance for each provider # because amazon returns all instances in a region, not # availability zone. if profile and alias not in self.opts['profiles'][profile]['provider'].split(':')[0]: continue for vm_name, details in six.iteritems(vms): # XXX: The logic below can be removed once the aws driver # is removed if vm_name not in names: continue elif driver == 'ec2' and 'aws' in handled_drivers and \ 'aws' in matches[handled_drivers['aws']] and \ vm_name in matches[handled_drivers['aws']]['aws']: continue elif driver == 'aws' and 'ec2' in handled_drivers and \ 'ec2' in matches[handled_drivers['ec2']] and \ vm_name in matches[handled_drivers['ec2']]['ec2']: continue if alias not in matches: matches[alias] = {} if driver not in matches[alias]: matches[alias][driver] = {} matches[alias][driver][vm_name] = details return matches def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers def location_list(self, lookup='all'): ''' Return a mapping of all location data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_locations'.format(driver) if fun not in self.clouds: # The capability to gather locations is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the locations information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def size_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_sizes'.format(driver) if fun not in self.clouds: # The capability to gather sizes is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the sizes information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output @staticmethod def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret def do_function(self, prov, func, kwargs): ''' Perform a function against a cloud provider ''' matches = self.lookup_providers(prov) if len(matches) > 1: raise SaltCloudSystemExit( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}'.format( prov, ', '.join([ '{0}:{1}'.format(alias, driver) for (alias, driver) in matches ]) ) ) alias, driver = matches.pop() fun = '{0}.{1}'.format(driver, func) if fun not in self.clouds: raise SaltCloudSystemExit( 'The \'{0}\' cloud provider alias, for the \'{1}\' driver, does ' 'not define the function \'{2}\''.format(alias, driver, func) ) log.debug( 'Trying to execute \'%s\' with the following kwargs: %s', fun, kwargs ) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if kwargs: return { alias: { driver: self.clouds[fun]( call='function', kwargs=kwargs ) } } return { alias: { driver: self.clouds[fun](call='function') } } def __filter_non_working_providers(self): ''' Remove any mis-configured cloud providers from the available listing ''' for alias, drivers in six.iteritems(self.opts['providers'].copy()): for driver in drivers.copy(): fun = '{0}.get_configured_provider'.format(driver) if fun not in self.clouds: # Mis-configured provider that got removed? log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias, could not be loaded. ' 'Please check your provider configuration files and ' 'ensure all required dependencies are installed ' 'for the \'%s\' driver.\n' 'In rare cases, this could indicate the \'%s()\' ' 'function could not be found.\nRemoving \'%s\' from ' 'the available providers list', driver, alias, driver, fun, driver ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if self.clouds[fun]() is False: log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias is not properly ' 'configured. Removing it from the available ' 'providers list.', driver, alias ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) class Map(Cloud): ''' Create a VM stateful map execution object ''' def __init__(self, opts): Cloud.__init__(self, opts) self.rendered_map = self.read() def interpolated_map(self, query='list_nodes', cached=False): rendered_map = self.read().copy() interpolated_map = {} for profile, mapped_vms in six.iteritems(rendered_map): names = set(mapped_vms) if profile not in self.opts['profiles']: if 'Errors' not in interpolated_map: interpolated_map['Errors'] = {} msg = ( 'No provider for the mapped \'{0}\' profile was found. ' 'Skipped VMS: {1}'.format( profile, ', '.join(names) ) ) log.info(msg) interpolated_map['Errors'][profile] = msg continue matching = self.get_running_by_names(names, query, cached) for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for vm_name, vm_details in six.iteritems(vms): if alias not in interpolated_map: interpolated_map[alias] = {} if driver not in interpolated_map[alias]: interpolated_map[alias][driver] = {} interpolated_map[alias][driver][vm_name] = vm_details try: names.remove(vm_name) except KeyError: # If it's not there, then our job is already done pass if not names: continue profile_details = self.opts['profiles'][profile] alias, driver = profile_details['provider'].split(':') for vm_name in names: if alias not in interpolated_map: interpolated_map[alias] = {} if driver not in interpolated_map[alias]: interpolated_map[alias][driver] = {} interpolated_map[alias][driver][vm_name] = 'Absent' return interpolated_map def delete_map(self, query=None): query_map = self.interpolated_map(query=query) for alias, drivers in six.iteritems(query_map.copy()): for driver, vms in six.iteritems(drivers.copy()): for vm_name, vm_details in six.iteritems(vms.copy()): if vm_details == 'Absent': query_map[alias][driver].pop(vm_name) if not query_map[alias][driver]: query_map[alias].pop(driver) if not query_map[alias]: query_map.pop(alias) return query_map def get_vmnames_by_action(self, action): query_map = self.interpolated_map("list_nodes") matching_states = { 'start': ['stopped'], 'stop': ['running', 'active'], 'reboot': ['running', 'active'], } vm_names = [] for alias, drivers in six.iteritems(query_map): for driver, vms in six.iteritems(drivers): for vm_name, vm_details in six.iteritems(vms): # Only certain actions are support in to use in this case. Those actions are the # "Global" salt-cloud actions defined in the "matching_states" dictionary above. # If a more specific action is passed in, we shouldn't stack-trace - exit gracefully. try: state_action = matching_states[action] except KeyError: log.error( 'The use of \'%s\' as an action is not supported ' 'in this context. Only \'start\', \'stop\', and ' '\'reboot\' are supported options.', action ) raise SaltCloudException() if vm_details != 'Absent' and vm_details['state'].lower() in state_action: vm_names.append(vm_name) return vm_names def read(self): ''' Read in the specified map and return the map structure ''' map_ = None if self.opts.get('map', None) is None: if self.opts.get('map_data', None) is None: if self.opts.get('map_pillar', None) is None: pass elif self.opts.get('map_pillar') not in self.opts.get('maps'): log.error( 'The specified map not found in pillar at ' '\'cloud:maps:%s\'', self.opts['map_pillar'] ) raise SaltCloudNotFound() else: # 'map_pillar' is provided, try to use it map_ = self.opts['maps'][self.opts.get('map_pillar')] else: # 'map_data' is provided, try to use it map_ = self.opts['map_data'] else: # 'map' is provided, try to use it local_minion_opts = copy.deepcopy(self.opts) local_minion_opts['file_client'] = 'local' self.minion = salt.minion.MasterMinion(local_minion_opts) if not os.path.isfile(self.opts['map']): if not (self.opts['map']).startswith('salt://'): log.error( 'The specified map file does not exist: \'%s\'', self.opts['map'] ) raise SaltCloudNotFound() if (self.opts['map']).startswith('salt://'): cached_map = self.minion.functions['cp.cache_file'](self.opts['map']) else: cached_map = self.opts['map'] try: renderer = self.opts.get('renderer', 'jinja|yaml') rend = salt.loader.render(self.opts, {}) blacklist = self.opts.get('renderer_blacklist') whitelist = self.opts.get('renderer_whitelist') map_ = compile_template( cached_map, rend, renderer, blacklist, whitelist ) except Exception as exc: log.error( 'Rendering map %s failed, render error:\n%s', self.opts['map'], exc, exc_info_on_loglevel=logging.DEBUG ) return {} if 'include' in map_: map_ = salt.config.include_config( map_, self.opts['map'], verbose=False ) if not map_: return {} # Create expected data format if needed for profile, mapped in six.iteritems(map_.copy()): if isinstance(mapped, (list, tuple)): entries = {} for mapping in mapped: if isinstance(mapping, six.string_types): # Foo: # - bar1 # - bar2 mapping = {mapping: None} for name, overrides in six.iteritems(mapping): if overrides is None or isinstance(overrides, bool): # Foo: # - bar1: # - bar2: overrides = {} try: overrides.setdefault('name', name) except AttributeError: log.error( 'Cannot use \'name\' as a minion id in a cloud map as it ' 'is a reserved word. Please change \'name\' to a different ' 'minion id reference.' ) return {} entries[name] = overrides map_[profile] = entries continue if isinstance(mapped, dict): # Convert the dictionary mapping to a list of dictionaries # Foo: # bar1: # grains: # foo: bar # bar2: # grains: # foo: bar entries = {} for name, overrides in six.iteritems(mapped): overrides.setdefault('name', name) entries[name] = overrides map_[profile] = entries continue if isinstance(mapped, six.string_types): # If it's a single string entry, let's make iterable because of # the next step mapped = [mapped] map_[profile] = {} for name in mapped: map_[profile][name] = {'name': name} return map_ def _has_loop(self, dmap, seen=None, val=None): if seen is None: for values in six.itervalues(dmap['create']): seen = [] try: machines = values['requires'] except KeyError: machines = [] for machine in machines: if self._has_loop(dmap, seen=list(seen), val=machine): return True else: if val in seen: return True seen.append(val) try: machines = dmap['create'][val]['requires'] except KeyError: machines = [] for machine in machines: if self._has_loop(dmap, seen=list(seen), val=machine): return True return False def _calcdep(self, dmap, machine, data, level): try: deplist = data['requires'] except KeyError: return level levels = [] for name in deplist: try: data = dmap['create'][name] except KeyError: try: data = dmap['existing'][name] except KeyError: msg = 'Missing dependency in cloud map' log.error(msg) raise SaltCloudException(msg) levels.append(self._calcdep(dmap, name, data, level)) level = max(levels) + 1 return level def map_data(self, cached=False): ''' Create a data map of what to execute on ''' ret = {'create': {}} pmap = self.map_providers_parallel(cached=cached) exist = set() defined = set() rendered_map = copy.deepcopy(self.rendered_map) for profile_name, nodes in six.iteritems(rendered_map): if profile_name not in self.opts['profiles']: msg = ( 'The required profile, \'{0}\', defined in the map ' 'does not exist. The defined nodes, {1}, will not ' 'be created.'.format( profile_name, ', '.join('\'{0}\''.format(node) for node in nodes) ) ) log.error(msg) if 'errors' not in ret: ret['errors'] = {} ret['errors'][profile_name] = msg continue profile_data = self.opts['profiles'].get(profile_name) for nodename, overrides in six.iteritems(nodes): # Get associated provider data, in case something like size # or image is specified in the provider file. See issue #32510. if 'provider' in overrides and overrides['provider'] != profile_data['provider']: alias, driver = overrides.get('provider').split(':') else: alias, driver = profile_data.get('provider').split(':') provider_details = copy.deepcopy(self.opts['providers'][alias][driver]) del provider_details['profiles'] # Update the provider details information with profile data # Profile data and node overrides should override provider data, if defined. # This keeps map file data definitions consistent with -p usage. salt.utils.dictupdate.update(provider_details, profile_data) nodedata = copy.deepcopy(provider_details) # Update profile data with the map overrides for setting in ('grains', 'master', 'minion', 'volumes', 'requires'): deprecated = 'map_{0}'.format(setting) if deprecated in overrides: log.warning( 'The use of \'%s\' on the \'%s\' mapping has ' 'been deprecated. The preferred way now is to ' 'just define \'%s\'. For now, salt-cloud will do ' 'the proper thing and convert the deprecated ' 'mapping into the preferred one.', deprecated, nodename, setting ) overrides[setting] = overrides.pop(deprecated) # merge minion grains from map file if 'minion' in overrides and \ 'minion' in nodedata and \ 'grains' in overrides['minion'] and \ 'grains' in nodedata['minion']: nodedata['minion']['grains'].update( overrides['minion']['grains'] ) del overrides['minion']['grains'] # remove minion key if now is empty dict if not overrides['minion']: del overrides['minion'] nodedata = salt.utils.dictupdate.update(nodedata, overrides) # Add the computed information to the return data ret['create'][nodename] = nodedata # Add the node name to the defined set alias, driver = nodedata['provider'].split(':') defined.add((alias, driver, nodename)) def get_matching_by_name(name): matches = {} for alias, drivers in six.iteritems(pmap): for driver, vms in six.iteritems(drivers): for vm_name, details in six.iteritems(vms): if vm_name == name and driver not in matches: matches[driver] = details['state'] return matches for alias, drivers in six.iteritems(pmap): for driver, vms in six.iteritems(drivers): for name, details in six.iteritems(vms): exist.add((alias, driver, name)) if name not in ret['create']: continue # The machine is set to be created. Does it already exist? matching = get_matching_by_name(name) if not matching: continue # A machine by the same name exists for item in matching: if name not in ret['create']: # Machine already removed break log.warning("'%s' already exists, removing from " 'the create map.', name) if 'existing' not in ret: ret['existing'] = {} ret['existing'][name] = ret['create'].pop(name) if 'hard' in self.opts and self.opts['hard']: if self.opts['enable_hard_maps'] is False: raise SaltCloudSystemExit( 'The --hard map can be extremely dangerous to use, ' 'and therefore must explicitly be enabled in the main ' 'configuration file, by setting \'enable_hard_maps\' ' 'to True' ) # Hard maps are enabled, Look for the items to delete. ret['destroy'] = exist.difference(defined) return ret def run_map(self, dmap): ''' Execute the contents of the VM map ''' if self._has_loop(dmap): msg = 'Uh-oh, that cloud map has a dependency loop!' log.error(msg) raise SaltCloudException(msg) # Go through the create list and calc dependencies for key, val in six.iteritems(dmap['create']): log.info('Calculating dependencies for %s', key) level = 0 level = self._calcdep(dmap, key, val, level) log.debug('Got execution order %s for %s', level, key) dmap['create'][key]['level'] = level try: existing_list = six.iteritems(dmap['existing']) except KeyError: existing_list = six.iteritems({}) for key, val in existing_list: log.info('Calculating dependencies for %s', key) level = 0 level = self._calcdep(dmap, key, val, level) log.debug('Got execution order %s for %s', level, key) dmap['existing'][key]['level'] = level # Now sort the create list based on dependencies create_list = sorted(six.iteritems(dmap['create']), key=lambda x: x[1]['level']) full_map = dmap['create'].copy() if 'existing' in dmap: full_map.update(dmap['existing']) possible_master_list = sorted(six.iteritems(full_map), key=lambda x: x[1]['level']) output = {} if self.opts['parallel']: parallel_data = [] master_name = None master_minion_name = None master_host = None master_finger = None for name, profile in possible_master_list: if profile.get('make_master', False) is True: master_name = name master_profile = profile if master_name: # If the master already exists, get the host if master_name not in dmap['create']: master_host = self.client.query() for provider_part in master_profile['provider'].split(':'): master_host = master_host[provider_part] master_host = master_host[master_name][master_profile.get('ssh_interface', 'public_ips')] if not master_host: raise SaltCloudSystemExit( 'Could not get the hostname of master {}.'.format(master_name) ) # Otherwise, deploy it as a new master else: master_minion_name = master_name log.debug('Creating new master \'%s\'', master_name) if salt.config.get_cloud_config_value( 'deploy', master_profile, self.opts ) is False: raise SaltCloudSystemExit( 'Cannot proceed with \'make_master\' when salt deployment ' 'is disabled(ex: --no-deploy).' ) # Generate the master keys log.debug('Generating master keys for \'%s\'', master_profile['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', master_profile, self.opts ) ) master_profile['master_pub'] = pub master_profile['master_pem'] = priv # Generate the fingerprint of the master pubkey in order to # mitigate man-in-the-middle attacks master_temp_pub = salt.utils.files.mkstemp() with salt.utils.files.fopen(master_temp_pub, 'w') as mtp: mtp.write(pub) master_finger = salt.utils.crypt.pem_finger(master_temp_pub, sum_type=self.opts['hash_type']) os.unlink(master_temp_pub) if master_profile.get('make_minion', True) is True: master_profile.setdefault('minion', {}) if 'id' in master_profile['minion']: master_minion_name = master_profile['minion']['id'] # Set this minion's master as local if the user has not set it if 'master' not in master_profile['minion']: master_profile['minion']['master'] = '127.0.0.1' if master_finger is not None: master_profile['master_finger'] = master_finger # Generate the minion keys to pre-seed the master: for name, profile in create_list: make_minion = salt.config.get_cloud_config_value( 'make_minion', profile, self.opts, default=True ) if make_minion is False: continue log.debug('Generating minion keys for \'%s\'', profile['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', profile, self.opts ) ) profile['pub_key'] = pub profile['priv_key'] = priv # Store the minion's public key in order to be pre-seeded in # the master master_profile.setdefault('preseed_minion_keys', {}) master_profile['preseed_minion_keys'].update({name: pub}) local_master = False if master_profile['minion'].get('local_master', False) and \ master_profile['minion'].get('master', None) is not None: # The minion is explicitly defining a master and it's # explicitly saying it's the local one local_master = True out = self.create(master_profile, local_master=local_master) if not isinstance(out, dict): log.debug('Master creation details is not a dictionary: %s', out) elif 'Errors' in out: raise SaltCloudSystemExit( 'An error occurred while creating the master, not ' 'continuing: {0}'.format(out['Errors']) ) deploy_kwargs = ( self.opts.get('show_deploy_args', False) is True and # Get the needed data out.get('deploy_kwargs', {}) or # Strip the deploy_kwargs from the returned data since we don't # want it shown in the console. out.pop('deploy_kwargs', {}) ) master_host = deploy_kwargs.get('salt_host', deploy_kwargs.get('host', None)) if master_host is None: raise SaltCloudSystemExit( 'Host for new master {0} was not found, ' 'aborting map'.format( master_name ) ) output[master_name] = out else: log.debug('No make_master found in map') # Local master? # Generate the fingerprint of the master pubkey in order to # mitigate man-in-the-middle attacks master_pub = os.path.join(self.opts['pki_dir'], 'master.pub') if os.path.isfile(master_pub): master_finger = salt.utils.crypt.pem_finger(master_pub, sum_type=self.opts['hash_type']) opts = self.opts.copy() if self.opts['parallel']: # Force display_ssh_output to be False since the console will # need to be reset afterwards log.info( 'Since parallel deployment is in use, ssh console output ' 'is disabled. All ssh output will be logged though' ) opts['display_ssh_output'] = False local_master = master_name is None for name, profile in create_list: if name in (master_name, master_minion_name): # Already deployed, it's the master's minion continue if 'minion' in profile and profile['minion'].get('local_master', False) and \ profile['minion'].get('master', None) is not None: # The minion is explicitly defining a master and it's # explicitly saying it's the local one local_master = True if master_finger is not None and local_master is False: profile['master_finger'] = master_finger if master_host is not None: profile.setdefault('minion', {}) profile['minion'].setdefault('master', master_host) if self.opts['parallel']: parallel_data.append({ 'opts': opts, 'name': name, 'profile': profile, 'local_master': local_master }) continue # Not deploying in parallel try: output[name] = self.create( profile, local_master=local_master ) if self.opts.get('show_deploy_args', False) is False \ and 'deploy_kwargs' in output \ and isinstance(output[name], dict): output[name].pop('deploy_kwargs', None) except SaltCloudException as exc: log.error( 'Failed to deploy \'%s\'. Error: %s', name, exc, exc_info_on_loglevel=logging.DEBUG ) output[name] = {'Error': str(exc)} for name in dmap.get('destroy', ()): output[name] = self.destroy(name) if self.opts['parallel'] and parallel_data: if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Cloud pool size: %s', pool_size) output_multip = enter_mainloop( _create_multiprocessing, parallel_data, pool_size=pool_size) # We have deployed in parallel, now do start action in # correct order based on dependencies. if self.opts['start_action']: actionlist = [] grp = -1 for key, val in groupby(six.itervalues(dmap['create']), lambda x: x['level']): actionlist.append([]) grp += 1 for item in val: actionlist[grp].append(item['name']) out = {} for group in actionlist: log.info('Running %s on %s', self.opts['start_action'], ', '.join(group)) client = salt.client.get_local_client() out.update(client.cmd( ','.join(group), self.opts['start_action'], timeout=self.opts['timeout'] * 60, tgt_type='list' )) for obj in output_multip: next(six.itervalues(obj))['ret'] = out[next(six.iterkeys(obj))] output.update(obj) else: for obj in output_multip: output.update(obj) return output def init_pool_worker(): ''' Make every worker ignore KeyboarInterrup's since it will be handled by the parent process. ''' signal.signal(signal.SIGINT, signal.SIG_IGN) def create_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the create is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' cloud = Cloud(parallel_data['opts']) try: output = cloud.create( parallel_data['profile'], local_master=parallel_data['local_master'] ) except SaltCloudException as exc: log.error( 'Failed to deploy \'%s\'. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} if parallel_data['opts'].get('show_deploy_args', False) is False and isinstance(output, dict): output.pop('deploy_kwargs', None) return { parallel_data['name']: salt.utils.data.simple_types_filter(output) } def destroy_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the destroy is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' clouds = salt.loader.clouds(parallel_data['opts']) try: fun = clouds['{0}.destroy'.format(parallel_data['driver'])] with salt.utils.context.func_globals_inject( fun, __active_provider_name__=':'.join([ parallel_data['alias'], parallel_data['driver'] ]) ): output = fun(parallel_data['name']) except SaltCloudException as exc: log.error( 'Failed to destroy %s. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} return { parallel_data['name']: salt.utils.data.simple_types_filter(output) } # for pickle and multiprocessing, we can't use directly decorators def _run_parallel_map_providers_query(*args, **kw): return communicator(run_parallel_map_providers_query)(*args[0], **kw) def _destroy_multiprocessing(*args, **kw): return communicator(destroy_multiprocessing)(*args[0], **kw) def _create_multiprocessing(*args, **kw): return communicator(create_multiprocessing)(*args[0], **kw)
saltstack/salt
salt/cloud/__init__.py
CloudClient._opts_defaults
python
def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts
Set the opts dict to defaults and allow for opts to be overridden in the kwargs
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L219-L257
[ "def itervalues(d, **kw):\n return d.itervalues(**kw)\n" ]
class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
saltstack/salt
salt/cloud/__init__.py
CloudClient.low
python
def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {}))
Pass the cloud function and low data structure to run
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L259-L265
[ "def format_call(fun,\n data,\n initial_ret=None,\n expected_extra_kws=(),\n is_class_method=None):\n '''\n Build the required arguments and keyword arguments required for the passed\n function.\n\n :param fun: The function to get the argspec from\n :param data: A dictionary containing the required data to build the\n arguments and keyword arguments.\n :param initial_ret: The initial return data pre-populated as dictionary or\n None\n :param expected_extra_kws: Any expected extra keyword argument names which\n should not trigger a :ref:`SaltInvocationError`\n :param is_class_method: Pass True if you are sure that the function being passed\n is a class method. The reason for this is that on Python 3\n ``inspect.ismethod`` only returns ``True`` for bound methods,\n while on Python 2, it returns ``True`` for bound and unbound\n methods. So, on Python 3, in case of a class method, you'd\n need the class to which the function belongs to be instantiated\n and this is not always wanted.\n :returns: A dictionary with the function required arguments and keyword\n arguments.\n '''\n ret = initial_ret is not None and initial_ret or {}\n\n ret['args'] = []\n ret['kwargs'] = OrderedDict()\n\n aspec = get_function_argspec(fun, is_class_method=is_class_method)\n\n arg_data = arg_lookup(fun, aspec)\n args = arg_data['args']\n kwargs = arg_data['kwargs']\n\n # Since we WILL be changing the data dictionary, let's change a copy of it\n data = data.copy()\n\n missing_args = []\n\n for key in kwargs:\n try:\n kwargs[key] = data.pop(key)\n except KeyError:\n # Let's leave the default value in place\n pass\n\n while args:\n arg = args.pop(0)\n try:\n ret['args'].append(data.pop(arg))\n except KeyError:\n missing_args.append(arg)\n\n if missing_args:\n used_args_count = len(ret['args']) + len(args)\n args_count = used_args_count + len(missing_args)\n raise SaltInvocationError(\n '{0} takes at least {1} argument{2} ({3} given)'.format(\n fun.__name__,\n args_count,\n args_count > 1 and 's' or '',\n used_args_count\n )\n )\n\n ret['kwargs'].update(kwargs)\n\n if aspec.keywords:\n # The function accepts **kwargs, any non expected extra keyword\n # arguments will made available.\n for key, value in six.iteritems(data):\n if key in expected_extra_kws:\n continue\n ret['kwargs'][key] = value\n\n # No need to check for extra keyword arguments since they are all\n # **kwargs now. Return\n return ret\n\n # Did not return yet? Lets gather any remaining and unexpected keyword\n # arguments\n extra = {}\n for key, value in six.iteritems(data):\n if key in expected_extra_kws:\n continue\n extra[key] = copy.deepcopy(value)\n\n if extra:\n # Found unexpected keyword arguments, raise an error to the user\n if len(extra) == 1:\n msg = '\\'{0[0]}\\' is an invalid keyword argument for \\'{1}\\''.format(\n list(extra.keys()),\n ret.get(\n # In case this is being called for a state module\n 'full',\n # Not a state module, build the name\n '{0}.{1}'.format(fun.__module__, fun.__name__)\n )\n )\n else:\n msg = '{0} and \\'{1}\\' are invalid keyword arguments for \\'{2}\\''.format(\n ', '.join(['\\'{0}\\''.format(e) for e in extra][:-1]),\n list(extra.keys())[-1],\n ret.get(\n # In case this is being called for a state module\n 'full',\n # Not a state module, build the name\n '{0}.{1}'.format(fun.__module__, fun.__name__)\n )\n )\n\n raise SaltInvocationError(msg)\n return ret\n" ]
class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
saltstack/salt
salt/cloud/__init__.py
CloudClient.list_sizes
python
def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) )
List all available sizes in configured cloud systems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L267-L274
[ "def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n", "def _opts_defaults(self, **kwargs):\n '''\n Set the opts dict to defaults and allow for opts to be overridden in\n the kwargs\n '''\n # Let's start with the default salt cloud configuration\n opts = salt.config.DEFAULT_CLOUD_OPTS.copy()\n # Update it with the loaded configuration\n opts.update(self.opts.copy())\n # Reset some of the settings to sane values\n opts['parallel'] = False\n opts['keep_tmp'] = False\n opts['deploy'] = True\n opts['update_bootstrap'] = False\n opts['show_deploy_args'] = False\n opts['script_args'] = ''\n # Update it with the passed kwargs\n if 'kwargs' in kwargs:\n opts.update(kwargs['kwargs'])\n opts.update(kwargs)\n profile = opts.get('profile', None)\n # filter other profiles if one is specified\n if profile:\n tmp_profiles = opts.get('profiles', {}).copy()\n for _profile in [a for a in tmp_profiles]:\n if not _profile == profile:\n tmp_profiles.pop(_profile)\n # if profile is specified and we have enough info about providers\n # also filter them to speedup methods like\n # __filter_non_working_providers\n providers = [a.get('provider', '').split(':')[0]\n for a in six.itervalues(tmp_profiles)\n if a.get('provider', '')]\n if providers:\n _providers = opts.get('providers', {})\n for provider in _providers.copy():\n if provider not in providers:\n _providers.pop(provider)\n return opts\n", "def size_list(self, lookup='all'):\n '''\n Return a mapping of all image data for available providers\n '''\n data = {}\n\n lookups = self.lookup_providers(lookup)\n if not lookups:\n return data\n\n for alias, driver in lookups:\n fun = '{0}.avail_sizes'.format(driver)\n if fun not in self.clouds:\n # The capability to gather sizes is not supported by this\n # cloud module\n log.debug(\n 'The \\'%s\\' cloud driver defined under \\'%s\\' provider '\n 'alias is unable to get the sizes information',\n driver, alias\n )\n continue\n\n if alias not in data:\n data[alias] = {}\n\n try:\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=':'.join([alias, driver])\n ):\n data[alias][driver] = self.clouds[fun]()\n except Exception as err:\n log.error(\n 'Failed to get the output of \\'%s()\\': %s',\n fun, err, exc_info_on_loglevel=logging.DEBUG\n )\n return data\n" ]
class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
saltstack/salt
salt/cloud/__init__.py
CloudClient.list_images
python
def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) )
List all available images in configured cloud systems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L276-L283
[ "def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n", "def _opts_defaults(self, **kwargs):\n '''\n Set the opts dict to defaults and allow for opts to be overridden in\n the kwargs\n '''\n # Let's start with the default salt cloud configuration\n opts = salt.config.DEFAULT_CLOUD_OPTS.copy()\n # Update it with the loaded configuration\n opts.update(self.opts.copy())\n # Reset some of the settings to sane values\n opts['parallel'] = False\n opts['keep_tmp'] = False\n opts['deploy'] = True\n opts['update_bootstrap'] = False\n opts['show_deploy_args'] = False\n opts['script_args'] = ''\n # Update it with the passed kwargs\n if 'kwargs' in kwargs:\n opts.update(kwargs['kwargs'])\n opts.update(kwargs)\n profile = opts.get('profile', None)\n # filter other profiles if one is specified\n if profile:\n tmp_profiles = opts.get('profiles', {}).copy()\n for _profile in [a for a in tmp_profiles]:\n if not _profile == profile:\n tmp_profiles.pop(_profile)\n # if profile is specified and we have enough info about providers\n # also filter them to speedup methods like\n # __filter_non_working_providers\n providers = [a.get('provider', '').split(':')[0]\n for a in six.itervalues(tmp_profiles)\n if a.get('provider', '')]\n if providers:\n _providers = opts.get('providers', {})\n for provider in _providers.copy():\n if provider not in providers:\n _providers.pop(provider)\n return opts\n", "def image_list(self, lookup='all'):\n '''\n Return a mapping of all image data for available providers\n '''\n data = {}\n\n lookups = self.lookup_providers(lookup)\n if not lookups:\n return data\n\n for alias, driver in lookups:\n fun = '{0}.avail_images'.format(driver)\n if fun not in self.clouds:\n # The capability to gather images is not supported by this\n # cloud module\n log.debug(\n 'The \\'%s\\' cloud driver defined under \\'%s\\' provider '\n 'alias is unable to get the images information',\n driver, alias\n )\n continue\n\n if alias not in data:\n data[alias] = {}\n\n try:\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=':'.join([alias, driver])\n ):\n data[alias][driver] = self.clouds[fun]()\n except Exception as err:\n log.error(\n 'Failed to get the output of \\'%s()\\': %s',\n fun, err, exc_info_on_loglevel=logging.DEBUG\n )\n return data\n" ]
class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
saltstack/salt
salt/cloud/__init__.py
CloudClient.list_locations
python
def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) )
List all available locations in configured cloud systems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L285-L292
[ "def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n", "def _opts_defaults(self, **kwargs):\n '''\n Set the opts dict to defaults and allow for opts to be overridden in\n the kwargs\n '''\n # Let's start with the default salt cloud configuration\n opts = salt.config.DEFAULT_CLOUD_OPTS.copy()\n # Update it with the loaded configuration\n opts.update(self.opts.copy())\n # Reset some of the settings to sane values\n opts['parallel'] = False\n opts['keep_tmp'] = False\n opts['deploy'] = True\n opts['update_bootstrap'] = False\n opts['show_deploy_args'] = False\n opts['script_args'] = ''\n # Update it with the passed kwargs\n if 'kwargs' in kwargs:\n opts.update(kwargs['kwargs'])\n opts.update(kwargs)\n profile = opts.get('profile', None)\n # filter other profiles if one is specified\n if profile:\n tmp_profiles = opts.get('profiles', {}).copy()\n for _profile in [a for a in tmp_profiles]:\n if not _profile == profile:\n tmp_profiles.pop(_profile)\n # if profile is specified and we have enough info about providers\n # also filter them to speedup methods like\n # __filter_non_working_providers\n providers = [a.get('provider', '').split(':')[0]\n for a in six.itervalues(tmp_profiles)\n if a.get('provider', '')]\n if providers:\n _providers = opts.get('providers', {})\n for provider in _providers.copy():\n if provider not in providers:\n _providers.pop(provider)\n return opts\n", "def location_list(self, lookup='all'):\n '''\n Return a mapping of all location data for available providers\n '''\n data = {}\n\n lookups = self.lookup_providers(lookup)\n if not lookups:\n return data\n\n for alias, driver in lookups:\n fun = '{0}.avail_locations'.format(driver)\n if fun not in self.clouds:\n # The capability to gather locations is not supported by this\n # cloud module\n log.debug(\n 'The \\'%s\\' cloud driver defined under \\'%s\\' provider '\n 'alias is unable to get the locations information',\n driver, alias\n )\n continue\n\n if alias not in data:\n data[alias] = {}\n\n try:\n\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=':'.join([alias, driver])\n ):\n data[alias][driver] = self.clouds[fun]()\n except Exception as err:\n log.error(\n 'Failed to get the output of \\'%s()\\': %s',\n fun, err, exc_info_on_loglevel=logging.DEBUG\n )\n return data\n" ]
class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
saltstack/salt
salt/cloud/__init__.py
CloudClient.min_query
python
def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type)
Query select instance information
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L318-L324
[ "def _opts_defaults(self, **kwargs):\n '''\n Set the opts dict to defaults and allow for opts to be overridden in\n the kwargs\n '''\n # Let's start with the default salt cloud configuration\n opts = salt.config.DEFAULT_CLOUD_OPTS.copy()\n # Update it with the loaded configuration\n opts.update(self.opts.copy())\n # Reset some of the settings to sane values\n opts['parallel'] = False\n opts['keep_tmp'] = False\n opts['deploy'] = True\n opts['update_bootstrap'] = False\n opts['show_deploy_args'] = False\n opts['script_args'] = ''\n # Update it with the passed kwargs\n if 'kwargs' in kwargs:\n opts.update(kwargs['kwargs'])\n opts.update(kwargs)\n profile = opts.get('profile', None)\n # filter other profiles if one is specified\n if profile:\n tmp_profiles = opts.get('profiles', {}).copy()\n for _profile in [a for a in tmp_profiles]:\n if not _profile == profile:\n tmp_profiles.pop(_profile)\n # if profile is specified and we have enough info about providers\n # also filter them to speedup methods like\n # __filter_non_working_providers\n providers = [a.get('provider', '').split(':')[0]\n for a in six.itervalues(tmp_profiles)\n if a.get('provider', '')]\n if providers:\n _providers = opts.get('providers', {})\n for provider in _providers.copy():\n if provider not in providers:\n _providers.pop(provider)\n return opts\n", "def map_providers_parallel(self, query='list_nodes', cached=False):\n '''\n Return a mapping of what named VMs are running on what VM providers\n based on what providers are defined in the configuration and VMs\n\n Same as map_providers but query in parallel.\n '''\n if cached is True and query in self.__cached_provider_queries:\n return self.__cached_provider_queries[query]\n\n opts = self.opts.copy()\n multiprocessing_data = []\n\n # Optimize Providers\n opts['providers'] = self._optimize_providers(opts['providers'])\n for alias, drivers in six.iteritems(opts['providers']):\n # Make temp query for this driver to avoid overwrite next\n this_query = query\n for driver, details in six.iteritems(drivers):\n # If driver has function list_nodes_min, just replace it\n # with query param to check existing vms on this driver\n # for minimum information, Otherwise still use query param.\n if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds:\n this_query = 'list_nodes_min'\n\n fun = '{0}.{1}'.format(driver, this_query)\n if fun not in self.clouds:\n log.error('Public cloud provider %s is not available', driver)\n continue\n\n multiprocessing_data.append({\n 'fun': fun,\n 'opts': opts,\n 'query': this_query,\n 'alias': alias,\n 'driver': driver\n })\n output = {}\n if not multiprocessing_data:\n return output\n\n data_count = len(multiprocessing_data)\n pool = multiprocessing.Pool(data_count < 10 and data_count or 10,\n init_pool_worker)\n parallel_pmap = enter_mainloop(_run_parallel_map_providers_query,\n multiprocessing_data,\n pool=pool)\n for alias, driver, details in parallel_pmap:\n if not details:\n # There's no providers details?! Skip it!\n continue\n if alias not in output:\n output[alias] = {}\n output[alias][driver] = details\n\n self.__cached_provider_queries[query] = output\n return output\n" ]
class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
saltstack/salt
salt/cloud/__init__.py
CloudClient.profile
python
def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) )
Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L326-L366
[ "def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n", "def _opts_defaults(self, **kwargs):\n '''\n Set the opts dict to defaults and allow for opts to be overridden in\n the kwargs\n '''\n # Let's start with the default salt cloud configuration\n opts = salt.config.DEFAULT_CLOUD_OPTS.copy()\n # Update it with the loaded configuration\n opts.update(self.opts.copy())\n # Reset some of the settings to sane values\n opts['parallel'] = False\n opts['keep_tmp'] = False\n opts['deploy'] = True\n opts['update_bootstrap'] = False\n opts['show_deploy_args'] = False\n opts['script_args'] = ''\n # Update it with the passed kwargs\n if 'kwargs' in kwargs:\n opts.update(kwargs['kwargs'])\n opts.update(kwargs)\n profile = opts.get('profile', None)\n # filter other profiles if one is specified\n if profile:\n tmp_profiles = opts.get('profiles', {}).copy()\n for _profile in [a for a in tmp_profiles]:\n if not _profile == profile:\n tmp_profiles.pop(_profile)\n # if profile is specified and we have enough info about providers\n # also filter them to speedup methods like\n # __filter_non_working_providers\n providers = [a.get('provider', '').split(':')[0]\n for a in six.itervalues(tmp_profiles)\n if a.get('provider', '')]\n if providers:\n _providers = opts.get('providers', {})\n for provider in _providers.copy():\n if provider not in providers:\n _providers.pop(provider)\n return opts\n", "def run_profile(self, profile, names, vm_overrides=None):\n '''\n Parse over the options passed on the command line and determine how to\n handle them\n '''\n if profile not in self.opts['profiles']:\n msg = 'Profile {0} is not defined'.format(profile)\n log.error(msg)\n return {'Error': msg}\n\n ret = {}\n if not vm_overrides:\n vm_overrides = {}\n\n try:\n with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc:\n main_cloud_config = salt.utils.yaml.safe_load(mcc)\n if not main_cloud_config:\n main_cloud_config = {}\n except KeyError:\n main_cloud_config = {}\n except IOError:\n main_cloud_config = {}\n\n if main_cloud_config is None:\n main_cloud_config = {}\n\n mapped_providers = self.map_providers_parallel()\n profile_details = self.opts['profiles'][profile]\n vms = {}\n for prov, val in six.iteritems(mapped_providers):\n prov_name = next(iter(val))\n for node in mapped_providers[prov][prov_name]:\n vms[node] = mapped_providers[prov][prov_name][node]\n vms[node]['provider'] = prov\n vms[node]['driver'] = prov_name\n alias, driver = profile_details['provider'].split(':')\n\n provider_details = self.opts['providers'][alias][driver].copy()\n del provider_details['profiles']\n\n for name in names:\n if name in vms:\n prov = vms[name]['provider']\n driv = vms[name]['driver']\n msg = '{0} already exists under {1}:{2}'.format(\n name, prov, driv\n )\n log.error(msg)\n ret[name] = {'Error': msg}\n continue\n\n vm_ = self.vm_config(\n name,\n main_cloud_config,\n provider_details,\n profile_details,\n vm_overrides,\n )\n if self.opts['parallel']:\n process = multiprocessing.Process(\n target=self.create,\n args=(vm_,)\n )\n process.start()\n ret[name] = {\n 'Provisioning': 'VM being provisioned in parallel. '\n 'PID: {0}'.format(process.pid)\n }\n continue\n\n try:\n # No need to inject __active_provider_name__ into the context\n # here because self.create takes care of that\n ret[name] = self.create(vm_)\n if not ret[name]:\n ret[name] = {'Error': 'Failed to deploy VM'}\n if len(names) == 1:\n raise SaltCloudSystemExit('Failed to deploy VM')\n continue\n if self.opts.get('show_deploy_args', False) is False:\n ret[name].pop('deploy_kwargs', None)\n except (SaltCloudSystemExit, SaltCloudConfigError) as exc:\n if len(names) == 1:\n raise\n ret[name] = {'Error': str(exc)}\n\n return ret\n" ]
class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
saltstack/salt
salt/cloud/__init__.py
CloudClient.map_run
python
def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) )
To execute a map
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L368-L380
[ "def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n", "def _opts_defaults(self, **kwargs):\n '''\n Set the opts dict to defaults and allow for opts to be overridden in\n the kwargs\n '''\n # Let's start with the default salt cloud configuration\n opts = salt.config.DEFAULT_CLOUD_OPTS.copy()\n # Update it with the loaded configuration\n opts.update(self.opts.copy())\n # Reset some of the settings to sane values\n opts['parallel'] = False\n opts['keep_tmp'] = False\n opts['deploy'] = True\n opts['update_bootstrap'] = False\n opts['show_deploy_args'] = False\n opts['script_args'] = ''\n # Update it with the passed kwargs\n if 'kwargs' in kwargs:\n opts.update(kwargs['kwargs'])\n opts.update(kwargs)\n profile = opts.get('profile', None)\n # filter other profiles if one is specified\n if profile:\n tmp_profiles = opts.get('profiles', {}).copy()\n for _profile in [a for a in tmp_profiles]:\n if not _profile == profile:\n tmp_profiles.pop(_profile)\n # if profile is specified and we have enough info about providers\n # also filter them to speedup methods like\n # __filter_non_working_providers\n providers = [a.get('provider', '').split(':')[0]\n for a in six.itervalues(tmp_profiles)\n if a.get('provider', '')]\n if providers:\n _providers = opts.get('providers', {})\n for provider in _providers.copy():\n if provider not in providers:\n _providers.pop(provider)\n return opts\n", "def map_data(self, cached=False):\n '''\n Create a data map of what to execute on\n '''\n ret = {'create': {}}\n pmap = self.map_providers_parallel(cached=cached)\n exist = set()\n defined = set()\n rendered_map = copy.deepcopy(self.rendered_map)\n for profile_name, nodes in six.iteritems(rendered_map):\n if profile_name not in self.opts['profiles']:\n msg = (\n 'The required profile, \\'{0}\\', defined in the map '\n 'does not exist. The defined nodes, {1}, will not '\n 'be created.'.format(\n profile_name,\n ', '.join('\\'{0}\\''.format(node) for node in nodes)\n )\n )\n log.error(msg)\n if 'errors' not in ret:\n ret['errors'] = {}\n ret['errors'][profile_name] = msg\n continue\n\n profile_data = self.opts['profiles'].get(profile_name)\n\n for nodename, overrides in six.iteritems(nodes):\n # Get associated provider data, in case something like size\n # or image is specified in the provider file. See issue #32510.\n if 'provider' in overrides and overrides['provider'] != profile_data['provider']:\n alias, driver = overrides.get('provider').split(':')\n else:\n alias, driver = profile_data.get('provider').split(':')\n\n provider_details = copy.deepcopy(self.opts['providers'][alias][driver])\n del provider_details['profiles']\n\n # Update the provider details information with profile data\n # Profile data and node overrides should override provider data, if defined.\n # This keeps map file data definitions consistent with -p usage.\n salt.utils.dictupdate.update(provider_details, profile_data)\n nodedata = copy.deepcopy(provider_details)\n\n # Update profile data with the map overrides\n for setting in ('grains', 'master', 'minion', 'volumes',\n 'requires'):\n deprecated = 'map_{0}'.format(setting)\n if deprecated in overrides:\n log.warning(\n 'The use of \\'%s\\' on the \\'%s\\' mapping has '\n 'been deprecated. The preferred way now is to '\n 'just define \\'%s\\'. For now, salt-cloud will do '\n 'the proper thing and convert the deprecated '\n 'mapping into the preferred one.',\n deprecated, nodename, setting\n )\n overrides[setting] = overrides.pop(deprecated)\n\n # merge minion grains from map file\n if 'minion' in overrides and \\\n 'minion' in nodedata and \\\n 'grains' in overrides['minion'] and \\\n 'grains' in nodedata['minion']:\n nodedata['minion']['grains'].update(\n overrides['minion']['grains']\n )\n del overrides['minion']['grains']\n # remove minion key if now is empty dict\n if not overrides['minion']:\n del overrides['minion']\n\n nodedata = salt.utils.dictupdate.update(nodedata, overrides)\n # Add the computed information to the return data\n ret['create'][nodename] = nodedata\n # Add the node name to the defined set\n alias, driver = nodedata['provider'].split(':')\n defined.add((alias, driver, nodename))\n\n def get_matching_by_name(name):\n matches = {}\n for alias, drivers in six.iteritems(pmap):\n for driver, vms in six.iteritems(drivers):\n for vm_name, details in six.iteritems(vms):\n if vm_name == name and driver not in matches:\n matches[driver] = details['state']\n return matches\n\n for alias, drivers in six.iteritems(pmap):\n for driver, vms in six.iteritems(drivers):\n for name, details in six.iteritems(vms):\n exist.add((alias, driver, name))\n if name not in ret['create']:\n continue\n\n # The machine is set to be created. Does it already exist?\n matching = get_matching_by_name(name)\n if not matching:\n continue\n\n # A machine by the same name exists\n for item in matching:\n if name not in ret['create']:\n # Machine already removed\n break\n\n log.warning(\"'%s' already exists, removing from \"\n 'the create map.', name)\n\n if 'existing' not in ret:\n ret['existing'] = {}\n ret['existing'][name] = ret['create'].pop(name)\n\n if 'hard' in self.opts and self.opts['hard']:\n if self.opts['enable_hard_maps'] is False:\n raise SaltCloudSystemExit(\n 'The --hard map can be extremely dangerous to use, '\n 'and therefore must explicitly be enabled in the main '\n 'configuration file, by setting \\'enable_hard_maps\\' '\n 'to True'\n )\n\n # Hard maps are enabled, Look for the items to delete.\n ret['destroy'] = exist.difference(defined)\n return ret\n", "def run_map(self, dmap):\n '''\n Execute the contents of the VM map\n '''\n if self._has_loop(dmap):\n msg = 'Uh-oh, that cloud map has a dependency loop!'\n log.error(msg)\n raise SaltCloudException(msg)\n # Go through the create list and calc dependencies\n for key, val in six.iteritems(dmap['create']):\n log.info('Calculating dependencies for %s', key)\n level = 0\n level = self._calcdep(dmap, key, val, level)\n log.debug('Got execution order %s for %s', level, key)\n dmap['create'][key]['level'] = level\n\n try:\n existing_list = six.iteritems(dmap['existing'])\n except KeyError:\n existing_list = six.iteritems({})\n\n for key, val in existing_list:\n log.info('Calculating dependencies for %s', key)\n level = 0\n level = self._calcdep(dmap, key, val, level)\n log.debug('Got execution order %s for %s', level, key)\n dmap['existing'][key]['level'] = level\n\n # Now sort the create list based on dependencies\n create_list = sorted(six.iteritems(dmap['create']), key=lambda x: x[1]['level'])\n full_map = dmap['create'].copy()\n if 'existing' in dmap:\n full_map.update(dmap['existing'])\n possible_master_list = sorted(six.iteritems(full_map), key=lambda x: x[1]['level'])\n output = {}\n if self.opts['parallel']:\n parallel_data = []\n master_name = None\n master_minion_name = None\n master_host = None\n master_finger = None\n for name, profile in possible_master_list:\n if profile.get('make_master', False) is True:\n master_name = name\n master_profile = profile\n\n if master_name:\n # If the master already exists, get the host\n if master_name not in dmap['create']:\n master_host = self.client.query()\n for provider_part in master_profile['provider'].split(':'):\n master_host = master_host[provider_part]\n master_host = master_host[master_name][master_profile.get('ssh_interface', 'public_ips')]\n if not master_host:\n raise SaltCloudSystemExit(\n 'Could not get the hostname of master {}.'.format(master_name)\n )\n # Otherwise, deploy it as a new master\n else:\n master_minion_name = master_name\n log.debug('Creating new master \\'%s\\'', master_name)\n if salt.config.get_cloud_config_value(\n 'deploy',\n master_profile,\n self.opts\n ) is False:\n raise SaltCloudSystemExit(\n 'Cannot proceed with \\'make_master\\' when salt deployment '\n 'is disabled(ex: --no-deploy).'\n )\n\n # Generate the master keys\n log.debug('Generating master keys for \\'%s\\'', master_profile['name'])\n\n priv, pub = salt.utils.cloud.gen_keys(\n salt.config.get_cloud_config_value(\n 'keysize',\n master_profile,\n self.opts\n )\n )\n master_profile['master_pub'] = pub\n master_profile['master_pem'] = priv\n\n # Generate the fingerprint of the master pubkey in order to\n # mitigate man-in-the-middle attacks\n master_temp_pub = salt.utils.files.mkstemp()\n with salt.utils.files.fopen(master_temp_pub, 'w') as mtp:\n mtp.write(pub)\n master_finger = salt.utils.crypt.pem_finger(master_temp_pub, sum_type=self.opts['hash_type'])\n os.unlink(master_temp_pub)\n\n if master_profile.get('make_minion', True) is True:\n master_profile.setdefault('minion', {})\n if 'id' in master_profile['minion']:\n master_minion_name = master_profile['minion']['id']\n # Set this minion's master as local if the user has not set it\n if 'master' not in master_profile['minion']:\n master_profile['minion']['master'] = '127.0.0.1'\n if master_finger is not None:\n master_profile['master_finger'] = master_finger\n\n # Generate the minion keys to pre-seed the master:\n for name, profile in create_list:\n make_minion = salt.config.get_cloud_config_value(\n 'make_minion', profile, self.opts, default=True\n )\n if make_minion is False:\n continue\n\n log.debug('Generating minion keys for \\'%s\\'', profile['name'])\n priv, pub = salt.utils.cloud.gen_keys(\n salt.config.get_cloud_config_value(\n 'keysize',\n profile,\n self.opts\n )\n )\n profile['pub_key'] = pub\n profile['priv_key'] = priv\n # Store the minion's public key in order to be pre-seeded in\n # the master\n master_profile.setdefault('preseed_minion_keys', {})\n master_profile['preseed_minion_keys'].update({name: pub})\n\n local_master = False\n if master_profile['minion'].get('local_master', False) and \\\n master_profile['minion'].get('master', None) is not None:\n # The minion is explicitly defining a master and it's\n # explicitly saying it's the local one\n local_master = True\n\n out = self.create(master_profile, local_master=local_master)\n\n if not isinstance(out, dict):\n log.debug('Master creation details is not a dictionary: %s', out)\n\n elif 'Errors' in out:\n raise SaltCloudSystemExit(\n 'An error occurred while creating the master, not '\n 'continuing: {0}'.format(out['Errors'])\n )\n\n deploy_kwargs = (\n self.opts.get('show_deploy_args', False) is True and\n # Get the needed data\n out.get('deploy_kwargs', {}) or\n # Strip the deploy_kwargs from the returned data since we don't\n # want it shown in the console.\n out.pop('deploy_kwargs', {})\n )\n\n master_host = deploy_kwargs.get('salt_host', deploy_kwargs.get('host', None))\n if master_host is None:\n raise SaltCloudSystemExit(\n 'Host for new master {0} was not found, '\n 'aborting map'.format(\n master_name\n )\n )\n output[master_name] = out\n else:\n log.debug('No make_master found in map')\n # Local master?\n # Generate the fingerprint of the master pubkey in order to\n # mitigate man-in-the-middle attacks\n master_pub = os.path.join(self.opts['pki_dir'], 'master.pub')\n if os.path.isfile(master_pub):\n master_finger = salt.utils.crypt.pem_finger(master_pub, sum_type=self.opts['hash_type'])\n\n opts = self.opts.copy()\n if self.opts['parallel']:\n # Force display_ssh_output to be False since the console will\n # need to be reset afterwards\n log.info(\n 'Since parallel deployment is in use, ssh console output '\n 'is disabled. All ssh output will be logged though'\n )\n opts['display_ssh_output'] = False\n\n local_master = master_name is None\n\n for name, profile in create_list:\n if name in (master_name, master_minion_name):\n # Already deployed, it's the master's minion\n continue\n\n if 'minion' in profile and profile['minion'].get('local_master', False) and \\\n profile['minion'].get('master', None) is not None:\n # The minion is explicitly defining a master and it's\n # explicitly saying it's the local one\n local_master = True\n\n if master_finger is not None and local_master is False:\n profile['master_finger'] = master_finger\n\n if master_host is not None:\n profile.setdefault('minion', {})\n profile['minion'].setdefault('master', master_host)\n\n if self.opts['parallel']:\n parallel_data.append({\n 'opts': opts,\n 'name': name,\n 'profile': profile,\n 'local_master': local_master\n })\n continue\n\n # Not deploying in parallel\n try:\n output[name] = self.create(\n profile, local_master=local_master\n )\n if self.opts.get('show_deploy_args', False) is False \\\n and 'deploy_kwargs' in output \\\n and isinstance(output[name], dict):\n output[name].pop('deploy_kwargs', None)\n except SaltCloudException as exc:\n log.error(\n 'Failed to deploy \\'%s\\'. Error: %s',\n name, exc, exc_info_on_loglevel=logging.DEBUG\n )\n output[name] = {'Error': str(exc)}\n\n for name in dmap.get('destroy', ()):\n output[name] = self.destroy(name)\n\n if self.opts['parallel'] and parallel_data:\n if 'pool_size' in self.opts:\n pool_size = self.opts['pool_size']\n else:\n pool_size = len(parallel_data)\n log.info('Cloud pool size: %s', pool_size)\n output_multip = enter_mainloop(\n _create_multiprocessing, parallel_data, pool_size=pool_size)\n # We have deployed in parallel, now do start action in\n # correct order based on dependencies.\n if self.opts['start_action']:\n actionlist = []\n grp = -1\n for key, val in groupby(six.itervalues(dmap['create']), lambda x: x['level']):\n actionlist.append([])\n grp += 1\n for item in val:\n actionlist[grp].append(item['name'])\n\n out = {}\n for group in actionlist:\n log.info('Running %s on %s', self.opts['start_action'], ', '.join(group))\n client = salt.client.get_local_client()\n out.update(client.cmd(\n ','.join(group), self.opts['start_action'],\n timeout=self.opts['timeout'] * 60, tgt_type='list'\n ))\n for obj in output_multip:\n next(six.itervalues(obj))['ret'] = out[next(six.iterkeys(obj))]\n output.update(obj)\n else:\n for obj in output_multip:\n output.update(obj)\n\n return output\n" ]
class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
saltstack/salt
salt/cloud/__init__.py
CloudClient.destroy
python
def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) )
Destroy the named VMs
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L382-L391
[ "def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n", "def _opts_defaults(self, **kwargs):\n '''\n Set the opts dict to defaults and allow for opts to be overridden in\n the kwargs\n '''\n # Let's start with the default salt cloud configuration\n opts = salt.config.DEFAULT_CLOUD_OPTS.copy()\n # Update it with the loaded configuration\n opts.update(self.opts.copy())\n # Reset some of the settings to sane values\n opts['parallel'] = False\n opts['keep_tmp'] = False\n opts['deploy'] = True\n opts['update_bootstrap'] = False\n opts['show_deploy_args'] = False\n opts['script_args'] = ''\n # Update it with the passed kwargs\n if 'kwargs' in kwargs:\n opts.update(kwargs['kwargs'])\n opts.update(kwargs)\n profile = opts.get('profile', None)\n # filter other profiles if one is specified\n if profile:\n tmp_profiles = opts.get('profiles', {}).copy()\n for _profile in [a for a in tmp_profiles]:\n if not _profile == profile:\n tmp_profiles.pop(_profile)\n # if profile is specified and we have enough info about providers\n # also filter them to speedup methods like\n # __filter_non_working_providers\n providers = [a.get('provider', '').split(':')[0]\n for a in six.itervalues(tmp_profiles)\n if a.get('provider', '')]\n if providers:\n _providers = opts.get('providers', {})\n for provider in _providers.copy():\n if provider not in providers:\n _providers.pop(provider)\n return opts\n", "def destroy(self, names, cached=False):\n '''\n Destroy the named VMs\n '''\n processed = {}\n names = set(names)\n matching = self.get_running_by_names(names, cached=cached)\n vms_to_destroy = set()\n parallel_data = []\n for alias, drivers in six.iteritems(matching):\n for driver, vms in six.iteritems(drivers):\n for name in vms:\n if name in names:\n vms_to_destroy.add((alias, driver, name))\n if self.opts['parallel']:\n parallel_data.append({\n 'opts': self.opts,\n 'name': name,\n 'alias': alias,\n 'driver': driver,\n })\n\n # destroying in parallel\n if self.opts['parallel'] and parallel_data:\n # set the pool size based on configuration or default to\n # the number of machines we're destroying\n if 'pool_size' in self.opts:\n pool_size = self.opts['pool_size']\n else:\n pool_size = len(parallel_data)\n log.info('Destroying in parallel mode; '\n 'Cloud pool size: %s', pool_size)\n\n # kick off the parallel destroy\n output_multip = enter_mainloop(\n _destroy_multiprocessing, parallel_data, pool_size=pool_size)\n\n # massage the multiprocessing output a bit\n ret_multip = {}\n for obj in output_multip:\n ret_multip.update(obj)\n\n # build up a data structure similar to what the non-parallel\n # destroy uses\n for obj in parallel_data:\n alias = obj['alias']\n driver = obj['driver']\n name = obj['name']\n if alias not in processed:\n processed[alias] = {}\n if driver not in processed[alias]:\n processed[alias][driver] = {}\n processed[alias][driver][name] = ret_multip[name]\n if name in names:\n names.remove(name)\n\n # not destroying in parallel\n else:\n log.info('Destroying in non-parallel mode.')\n for alias, driver, name in vms_to_destroy:\n fun = '{0}.destroy'.format(driver)\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=':'.join([alias, driver])\n ):\n ret = self.clouds[fun](name)\n if alias not in processed:\n processed[alias] = {}\n if driver not in processed[alias]:\n processed[alias][driver] = {}\n processed[alias][driver][name] = ret\n if name in names:\n names.remove(name)\n\n # now the processed data structure contains the output from either\n # the parallel or non-parallel destroy and we should finish up\n # with removing minion keys if necessary\n for alias, driver, name in vms_to_destroy:\n ret = processed[alias][driver][name]\n if not ret:\n continue\n\n vm_ = {\n 'name': name,\n 'profile': None,\n 'provider': ':'.join([alias, driver]),\n 'driver': driver\n }\n minion_dict = salt.config.get_cloud_config_value(\n 'minion', vm_, self.opts, default={}\n )\n key_file = os.path.join(\n self.opts['pki_dir'], 'minions', minion_dict.get('id', name)\n )\n globbed_key_file = glob.glob('{0}.*'.format(key_file))\n\n if not os.path.isfile(key_file) and not globbed_key_file:\n # There's no such key file!? It might have been renamed\n if isinstance(ret, dict) and 'newname' in ret:\n salt.utils.cloud.remove_key(\n self.opts['pki_dir'], ret['newname']\n )\n continue\n\n if os.path.isfile(key_file) and not globbed_key_file:\n # Single key entry. Remove it!\n salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file))\n continue\n\n # Since we have globbed matches, there are probably some keys for which their minion\n # configuration has append_domain set.\n if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1:\n # Single entry, let's remove it!\n salt.utils.cloud.remove_key(\n self.opts['pki_dir'],\n os.path.basename(globbed_key_file[0])\n )\n continue\n\n # Since we can't get the profile or map entry used to create\n # the VM, we can't also get the append_domain setting.\n # And if we reached this point, we have several minion keys\n # who's name starts with the machine name we're deleting.\n # We need to ask one by one!?\n print(\n 'There are several minion keys who\\'s name starts '\n 'with \\'{0}\\'. We need to ask you which one should be '\n 'deleted:'.format(\n name\n )\n )\n while True:\n for idx, filename in enumerate(globbed_key_file):\n print(' {0}: {1}'.format(\n idx, os.path.basename(filename)\n ))\n selection = input(\n 'Which minion key should be deleted(number)? '\n )\n try:\n selection = int(selection)\n except ValueError:\n print(\n '\\'{0}\\' is not a valid selection.'.format(selection)\n )\n\n try:\n filename = os.path.basename(\n globbed_key_file.pop(selection)\n )\n except Exception:\n continue\n\n delete = input(\n 'Delete \\'{0}\\'? [Y/n]? '.format(filename)\n )\n if delete == '' or delete.lower().startswith('y'):\n salt.utils.cloud.remove_key(\n self.opts['pki_dir'], filename\n )\n print('Deleted \\'{0}\\''.format(filename))\n break\n\n print('Did not delete \\'{0}\\''.format(filename))\n break\n\n if names and not processed:\n # These machines were asked to be destroyed but could not be found\n raise SaltCloudSystemExit(\n 'The following VM\\'s were not found: {0}'.format(\n ', '.join(names)\n )\n )\n\n elif names and processed:\n processed['Not Found'] = names\n\n elif not processed:\n raise SaltCloudSystemExit('No machines were destroyed!')\n\n return processed\n" ]
class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
saltstack/salt
salt/cloud/__init__.py
CloudClient.create
python
def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret
Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L393-L430
[ "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n", "def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n", "def _opts_defaults(self, **kwargs):\n '''\n Set the opts dict to defaults and allow for opts to be overridden in\n the kwargs\n '''\n # Let's start with the default salt cloud configuration\n opts = salt.config.DEFAULT_CLOUD_OPTS.copy()\n # Update it with the loaded configuration\n opts.update(self.opts.copy())\n # Reset some of the settings to sane values\n opts['parallel'] = False\n opts['keep_tmp'] = False\n opts['deploy'] = True\n opts['update_bootstrap'] = False\n opts['show_deploy_args'] = False\n opts['script_args'] = ''\n # Update it with the passed kwargs\n if 'kwargs' in kwargs:\n opts.update(kwargs['kwargs'])\n opts.update(kwargs)\n profile = opts.get('profile', None)\n # filter other profiles if one is specified\n if profile:\n tmp_profiles = opts.get('profiles', {}).copy()\n for _profile in [a for a in tmp_profiles]:\n if not _profile == profile:\n tmp_profiles.pop(_profile)\n # if profile is specified and we have enough info about providers\n # also filter them to speedup methods like\n # __filter_non_working_providers\n providers = [a.get('provider', '').split(':')[0]\n for a in six.itervalues(tmp_profiles)\n if a.get('provider', '')]\n if providers:\n _providers = opts.get('providers', {})\n for provider in _providers.copy():\n if provider not in providers:\n _providers.pop(provider)\n return opts\n", "def create(self, vm_, local_master=True):\n '''\n Create a single VM\n '''\n output = {}\n\n minion_dict = salt.config.get_cloud_config_value(\n 'minion', vm_, self.opts, default={}\n )\n\n alias, driver = vm_['provider'].split(':')\n fun = '{0}.create'.format(driver)\n if fun not in self.clouds:\n log.error(\n 'Creating \\'%s\\' using \\'%s\\' as the provider '\n 'cannot complete since \\'%s\\' is not available',\n vm_['name'], vm_['provider'], driver\n )\n return\n\n deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts)\n make_master = salt.config.get_cloud_config_value(\n 'make_master',\n vm_,\n self.opts\n )\n\n if deploy:\n if not make_master and 'master' not in minion_dict:\n log.warning(\n 'There\\'s no master defined on the \\'%s\\' VM settings.',\n vm_['name']\n )\n\n if 'pub_key' not in vm_ and 'priv_key' not in vm_:\n log.debug('Generating minion keys for \\'%s\\'', vm_['name'])\n priv, pub = salt.utils.cloud.gen_keys(\n salt.config.get_cloud_config_value(\n 'keysize',\n vm_,\n self.opts\n )\n )\n vm_['pub_key'] = pub\n vm_['priv_key'] = priv\n else:\n # Note(pabelanger): We still reference pub_key and priv_key when\n # deploy is disabled.\n vm_['pub_key'] = None\n vm_['priv_key'] = None\n\n key_id = minion_dict.get('id', vm_['name'])\n\n domain = vm_.get('domain')\n if vm_.get('use_fqdn') and domain:\n minion_dict['append_domain'] = domain\n\n if 'append_domain' in minion_dict:\n key_id = '.'.join([key_id, minion_dict['append_domain']])\n\n if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_:\n log.debug('Generating the master keys for \\'%s\\'', vm_['name'])\n master_priv, master_pub = salt.utils.cloud.gen_keys(\n salt.config.get_cloud_config_value(\n 'keysize',\n vm_,\n self.opts\n )\n )\n vm_['master_pub'] = master_pub\n vm_['master_pem'] = master_priv\n\n if local_master is True and deploy is True:\n # Accept the key on the local master\n salt.utils.cloud.accept_key(\n self.opts['pki_dir'], vm_['pub_key'], key_id\n )\n\n vm_['os'] = salt.config.get_cloud_config_value(\n 'script',\n vm_,\n self.opts\n )\n\n try:\n vm_['inline_script'] = salt.config.get_cloud_config_value(\n 'inline_script',\n vm_,\n self.opts\n )\n except KeyError:\n pass\n\n try:\n alias, driver = vm_['provider'].split(':')\n func = '{0}.create'.format(driver)\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=':'.join([alias, driver])\n ):\n output = self.clouds[func](vm_)\n if output is not False and 'sync_after_install' in self.opts:\n if self.opts['sync_after_install'] not in (\n 'all', 'modules', 'states', 'grains'):\n log.error('Bad option for sync_after_install')\n return output\n\n # A small pause helps the sync work more reliably\n time.sleep(3)\n\n start = int(time.time())\n while int(time.time()) < start + 60:\n # We'll try every <timeout> seconds, up to a minute\n mopts_ = salt.config.DEFAULT_MASTER_OPTS\n conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1])\n mopts_.update(\n salt.config.master_config(\n os.path.join(conf_path,\n 'master')\n )\n )\n\n client = salt.client.get_local_client(mopts=mopts_)\n\n ret = client.cmd(\n vm_['name'],\n 'saltutil.sync_{0}'.format(self.opts['sync_after_install']),\n timeout=self.opts['timeout']\n )\n if ret:\n log.info(\n six.u('Synchronized the following dynamic modules: '\n ' {0}').format(ret)\n )\n break\n except KeyError as exc:\n log.exception(\n 'Failed to create VM %s. Configuration value %s needs '\n 'to be set', vm_['name'], exc\n )\n # If it's a map then we need to respect the 'requires'\n # so we do it later\n try:\n opt_map = self.opts['map']\n except KeyError:\n opt_map = False\n if self.opts['parallel'] and self.opts['start_action'] and not opt_map:\n log.info('Running %s on %s', self.opts['start_action'], vm_['name'])\n client = salt.client.get_local_client(mopts=self.opts)\n action_out = client.cmd(\n vm_['name'],\n self.opts['start_action'],\n timeout=self.opts['timeout'] * 60\n )\n output['ret'] = action_out\n return output\n" ]
class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
saltstack/salt
salt/cloud/__init__.py
CloudClient.extra_action
python
def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret
Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} )
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L432-L466
[ "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n", "def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n", "def _opts_defaults(self, **kwargs):\n '''\n Set the opts dict to defaults and allow for opts to be overridden in\n the kwargs\n '''\n # Let's start with the default salt cloud configuration\n opts = salt.config.DEFAULT_CLOUD_OPTS.copy()\n # Update it with the loaded configuration\n opts.update(self.opts.copy())\n # Reset some of the settings to sane values\n opts['parallel'] = False\n opts['keep_tmp'] = False\n opts['deploy'] = True\n opts['update_bootstrap'] = False\n opts['show_deploy_args'] = False\n opts['script_args'] = ''\n # Update it with the passed kwargs\n if 'kwargs' in kwargs:\n opts.update(kwargs['kwargs'])\n opts.update(kwargs)\n profile = opts.get('profile', None)\n # filter other profiles if one is specified\n if profile:\n tmp_profiles = opts.get('profiles', {}).copy()\n for _profile in [a for a in tmp_profiles]:\n if not _profile == profile:\n tmp_profiles.pop(_profile)\n # if profile is specified and we have enough info about providers\n # also filter them to speedup methods like\n # __filter_non_working_providers\n providers = [a.get('provider', '').split(':')[0]\n for a in six.itervalues(tmp_profiles)\n if a.get('provider', '')]\n if providers:\n _providers = opts.get('providers', {})\n for provider in _providers.copy():\n if provider not in providers:\n _providers.pop(provider)\n return opts\n", "def map_providers_parallel(self, query='list_nodes', cached=False):\n '''\n Return a mapping of what named VMs are running on what VM providers\n based on what providers are defined in the configuration and VMs\n\n Same as map_providers but query in parallel.\n '''\n if cached is True and query in self.__cached_provider_queries:\n return self.__cached_provider_queries[query]\n\n opts = self.opts.copy()\n multiprocessing_data = []\n\n # Optimize Providers\n opts['providers'] = self._optimize_providers(opts['providers'])\n for alias, drivers in six.iteritems(opts['providers']):\n # Make temp query for this driver to avoid overwrite next\n this_query = query\n for driver, details in six.iteritems(drivers):\n # If driver has function list_nodes_min, just replace it\n # with query param to check existing vms on this driver\n # for minimum information, Otherwise still use query param.\n if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds:\n this_query = 'list_nodes_min'\n\n fun = '{0}.{1}'.format(driver, this_query)\n if fun not in self.clouds:\n log.error('Public cloud provider %s is not available', driver)\n continue\n\n multiprocessing_data.append({\n 'fun': fun,\n 'opts': opts,\n 'query': this_query,\n 'alias': alias,\n 'driver': driver\n })\n output = {}\n if not multiprocessing_data:\n return output\n\n data_count = len(multiprocessing_data)\n pool = multiprocessing.Pool(data_count < 10 and data_count or 10,\n init_pool_worker)\n parallel_pmap = enter_mainloop(_run_parallel_map_providers_query,\n multiprocessing_data,\n pool=pool)\n for alias, driver, details in parallel_pmap:\n if not details:\n # There's no providers details?! Skip it!\n continue\n if alias not in output:\n output[alias] = {}\n output[alias][driver] = details\n\n self.__cached_provider_queries[query] = output\n return output\n", "def extras(self, extra_):\n '''\n Extra actions\n '''\n output = {}\n\n alias, driver = extra_['provider'].split(':')\n fun = '{0}.{1}'.format(driver, extra_['action'])\n if fun not in self.clouds:\n log.error(\n 'Creating \\'%s\\' using \\'%s\\' as the provider '\n 'cannot complete since \\'%s\\' is not available',\n extra_['name'], extra_['provider'], driver\n )\n return\n\n try:\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=extra_['provider']\n ):\n output = self.clouds[fun](**extra_)\n except KeyError as exc:\n log.exception(\n 'Failed to perform %s.%s on %s. '\n 'Configuration value %s needs to be set',\n extra_['provider'], extra_['action'], extra_['name'], exc\n )\n return output\n" ]
class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
saltstack/salt
salt/cloud/__init__.py
CloudClient.action
python
def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} )
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L468-L518
[ "def _opts_defaults(self, **kwargs):\n '''\n Set the opts dict to defaults and allow for opts to be overridden in\n the kwargs\n '''\n # Let's start with the default salt cloud configuration\n opts = salt.config.DEFAULT_CLOUD_OPTS.copy()\n # Update it with the loaded configuration\n opts.update(self.opts.copy())\n # Reset some of the settings to sane values\n opts['parallel'] = False\n opts['keep_tmp'] = False\n opts['deploy'] = True\n opts['update_bootstrap'] = False\n opts['show_deploy_args'] = False\n opts['script_args'] = ''\n # Update it with the passed kwargs\n if 'kwargs' in kwargs:\n opts.update(kwargs['kwargs'])\n opts.update(kwargs)\n profile = opts.get('profile', None)\n # filter other profiles if one is specified\n if profile:\n tmp_profiles = opts.get('profiles', {}).copy()\n for _profile in [a for a in tmp_profiles]:\n if not _profile == profile:\n tmp_profiles.pop(_profile)\n # if profile is specified and we have enough info about providers\n # also filter them to speedup methods like\n # __filter_non_working_providers\n providers = [a.get('provider', '').split(':')[0]\n for a in six.itervalues(tmp_profiles)\n if a.get('provider', '')]\n if providers:\n _providers = opts.get('providers', {})\n for provider in _providers.copy():\n if provider not in providers:\n _providers.pop(provider)\n return opts\n", "def do_action(self, names, kwargs):\n '''\n Perform an action on a VM which may be specific to this cloud provider\n '''\n ret = {}\n invalid_functions = {}\n names = set(names)\n\n for alias, drivers in six.iteritems(self.map_providers_parallel()):\n if not names:\n break\n for driver, vms in six.iteritems(drivers):\n if not names:\n break\n valid_function = True\n fun = '{0}.{1}'.format(driver, self.opts['action'])\n if fun not in self.clouds:\n log.info('\\'%s()\\' is not available. Not actioning...', fun)\n valid_function = False\n for vm_name, vm_details in six.iteritems(vms):\n if not names:\n break\n if vm_name not in names:\n if not isinstance(vm_details, dict):\n vm_details = {}\n if 'id' in vm_details and vm_details['id'] in names:\n vm_name = vm_details['id']\n else:\n log.debug(\n 'vm:%s in provider:%s is not in name '\n 'list:\\'%s\\'', vm_name, driver, names\n )\n continue\n\n # Build the dictionary of invalid functions with their associated VMs.\n if valid_function is False:\n if invalid_functions.get(fun) is None:\n invalid_functions.update({fun: []})\n invalid_functions[fun].append(vm_name)\n continue\n\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=':'.join([alias, driver])\n ):\n if alias not in ret:\n ret[alias] = {}\n if driver not in ret[alias]:\n ret[alias][driver] = {}\n\n # Clean kwargs of \"__pub_*\" data before running the cloud action call.\n # Prevents calling positional \"kwarg\" arg before \"call\" when no kwarg\n # argument is present in the cloud driver function's arg spec.\n kwargs = salt.utils.args.clean_kwargs(**kwargs)\n\n if kwargs:\n ret[alias][driver][vm_name] = self.clouds[fun](\n vm_name, kwargs, call='action'\n )\n else:\n ret[alias][driver][vm_name] = self.clouds[fun](\n vm_name, call='action'\n )\n names.remove(vm_name)\n\n # Set the return information for the VMs listed in the invalid_functions dict.\n missing_vms = set()\n if invalid_functions:\n ret['Invalid Actions'] = invalid_functions\n invalid_func_vms = set()\n for key, val in six.iteritems(invalid_functions):\n invalid_func_vms = invalid_func_vms.union(set(val))\n\n # Find the VMs that are in names, but not in set of invalid functions.\n missing_vms = names.difference(invalid_func_vms)\n if missing_vms:\n ret['Not Found'] = list(missing_vms)\n ret['Not Actioned/Not Running'] = list(names)\n\n if not names:\n return ret\n\n # Don't return missing VM information for invalid functions until after we've had a\n # Chance to return successful actions. If a function is valid for one driver, but\n # Not another, we want to make sure the successful action is returned properly.\n if missing_vms:\n return ret\n\n # If we reach this point, the Not Actioned and Not Found lists will be the same,\n # But we want to list both for clarity/consistency with the invalid functions lists.\n ret['Not Actioned/Not Running'] = list(names)\n ret['Not Found'] = list(names)\n return ret\n", "def do_function(self, prov, func, kwargs):\n '''\n Perform a function against a cloud provider\n '''\n matches = self.lookup_providers(prov)\n if len(matches) > 1:\n raise SaltCloudSystemExit(\n 'More than one results matched \\'{0}\\'. Please specify '\n 'one of: {1}'.format(\n prov,\n ', '.join([\n '{0}:{1}'.format(alias, driver) for\n (alias, driver) in matches\n ])\n )\n )\n\n alias, driver = matches.pop()\n fun = '{0}.{1}'.format(driver, func)\n if fun not in self.clouds:\n raise SaltCloudSystemExit(\n 'The \\'{0}\\' cloud provider alias, for the \\'{1}\\' driver, does '\n 'not define the function \\'{2}\\''.format(alias, driver, func)\n )\n\n log.debug(\n 'Trying to execute \\'%s\\' with the following kwargs: %s',\n fun, kwargs\n )\n\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=':'.join([alias, driver])\n ):\n if kwargs:\n return {\n alias: {\n driver: self.clouds[fun](\n call='function', kwargs=kwargs\n )\n }\n }\n return {\n alias: {\n driver: self.clouds[fun](call='function')\n }\n }\n" ]
class CloudClient(object): ''' The client class to wrap cloud interactions ''' def __init__(self, path=None, opts=None, config_dir=None, pillars=None): if opts: self.opts = opts elif path: self.opts = salt.config.cloud_config(path) else: self.opts = salt.config.cloud_config() # Check the cache-dir exists. If not, create it. v_dirs = [self.opts['cachedir']] salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user()) if pillars: for name, provider in six.iteritems(pillars.pop('providers', {})): driver = provider['driver'] provider['profiles'] = {} self.opts['providers'].update({name: {driver: provider}}) for name, profile in six.iteritems(pillars.pop('profiles', {})): provider = profile['provider'].split(':')[0] driver = next(six.iterkeys(self.opts['providers'][provider])) profile['provider'] = '{0}:{1}'.format(provider, driver) profile['profile'] = name self.opts['profiles'].update({name: profile}) self.opts['providers'][provider][driver]['profiles'].update({name: profile}) for name, map_dct in six.iteritems(pillars.pop('maps', {})): if 'maps' not in self.opts: self.opts['maps'] = {} self.opts['maps'][name] = map_dct self.opts.update(pillars) def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) ) def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) ) def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) ) def query(self, query_type='list_nodes'): ''' Query basic instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes' return mapper.map_providers_parallel(query_type) def full_query(self, query_type='list_nodes_full'): ''' Query all instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_full' return mapper.map_providers_parallel(query_type) def select_query(self, query_type='list_nodes_select'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_select' return mapper.map_providers_parallel(query_type) def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type) def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) ) def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) ) def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ) def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret
saltstack/salt
salt/cloud/__init__.py
Cloud.get_configured_providers
python
def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers
Return the configured providers
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L532-L543
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
class Cloud(object): ''' An object for the creation of new VMs ''' def __init__(self, opts): self.opts = opts self.client = CloudClient(opts=self.opts) self.clouds = salt.loader.clouds(self.opts) self.__filter_non_working_providers() self.__cached_provider_queries = {} def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output def get_running_by_names(self, names, query='list_nodes', cached=False, profile=None): if isinstance(names, six.string_types): names = [names] matches = {} handled_drivers = {} mapped_providers = self.map_providers_parallel(query, cached=cached) for alias, drivers in six.iteritems(mapped_providers): for driver, vms in six.iteritems(drivers): if driver not in handled_drivers: handled_drivers[driver] = alias # When a profile is specified, only return an instance # that matches the provider specified in the profile. # This solves the issues when many providers return the # same instance. For example there may be one provider for # each availability zone in amazon in the same region, but # the search returns the same instance for each provider # because amazon returns all instances in a region, not # availability zone. if profile and alias not in self.opts['profiles'][profile]['provider'].split(':')[0]: continue for vm_name, details in six.iteritems(vms): # XXX: The logic below can be removed once the aws driver # is removed if vm_name not in names: continue elif driver == 'ec2' and 'aws' in handled_drivers and \ 'aws' in matches[handled_drivers['aws']] and \ vm_name in matches[handled_drivers['aws']]['aws']: continue elif driver == 'aws' and 'ec2' in handled_drivers and \ 'ec2' in matches[handled_drivers['ec2']] and \ vm_name in matches[handled_drivers['ec2']]['ec2']: continue if alias not in matches: matches[alias] = {} if driver not in matches[alias]: matches[alias][driver] = {} matches[alias][driver][vm_name] = details return matches def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers def location_list(self, lookup='all'): ''' Return a mapping of all location data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_locations'.format(driver) if fun not in self.clouds: # The capability to gather locations is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the locations information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def size_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_sizes'.format(driver) if fun not in self.clouds: # The capability to gather sizes is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the sizes information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output @staticmethod def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret def do_function(self, prov, func, kwargs): ''' Perform a function against a cloud provider ''' matches = self.lookup_providers(prov) if len(matches) > 1: raise SaltCloudSystemExit( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}'.format( prov, ', '.join([ '{0}:{1}'.format(alias, driver) for (alias, driver) in matches ]) ) ) alias, driver = matches.pop() fun = '{0}.{1}'.format(driver, func) if fun not in self.clouds: raise SaltCloudSystemExit( 'The \'{0}\' cloud provider alias, for the \'{1}\' driver, does ' 'not define the function \'{2}\''.format(alias, driver, func) ) log.debug( 'Trying to execute \'%s\' with the following kwargs: %s', fun, kwargs ) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if kwargs: return { alias: { driver: self.clouds[fun]( call='function', kwargs=kwargs ) } } return { alias: { driver: self.clouds[fun](call='function') } } def __filter_non_working_providers(self): ''' Remove any mis-configured cloud providers from the available listing ''' for alias, drivers in six.iteritems(self.opts['providers'].copy()): for driver in drivers.copy(): fun = '{0}.get_configured_provider'.format(driver) if fun not in self.clouds: # Mis-configured provider that got removed? log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias, could not be loaded. ' 'Please check your provider configuration files and ' 'ensure all required dependencies are installed ' 'for the \'%s\' driver.\n' 'In rare cases, this could indicate the \'%s()\' ' 'function could not be found.\nRemoving \'%s\' from ' 'the available providers list', driver, alias, driver, fun, driver ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if self.clouds[fun]() is False: log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias is not properly ' 'configured. Removing it from the available ' 'providers list.', driver, alias ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias)
saltstack/salt
salt/cloud/__init__.py
Cloud.lookup_providers
python
def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers
Get a dict describing the configured providers
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L545-L587
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def get_configured_providers(self):\n '''\n Return the configured providers\n '''\n providers = set()\n for alias, drivers in six.iteritems(self.opts['providers']):\n if len(drivers) > 1:\n for driver in drivers:\n providers.add('{0}:{1}'.format(alias, driver))\n continue\n providers.add(alias)\n return providers\n" ]
class Cloud(object): ''' An object for the creation of new VMs ''' def __init__(self, opts): self.opts = opts self.client = CloudClient(opts=self.opts) self.clouds = salt.loader.clouds(self.opts) self.__filter_non_working_providers() self.__cached_provider_queries = {} def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output def get_running_by_names(self, names, query='list_nodes', cached=False, profile=None): if isinstance(names, six.string_types): names = [names] matches = {} handled_drivers = {} mapped_providers = self.map_providers_parallel(query, cached=cached) for alias, drivers in six.iteritems(mapped_providers): for driver, vms in six.iteritems(drivers): if driver not in handled_drivers: handled_drivers[driver] = alias # When a profile is specified, only return an instance # that matches the provider specified in the profile. # This solves the issues when many providers return the # same instance. For example there may be one provider for # each availability zone in amazon in the same region, but # the search returns the same instance for each provider # because amazon returns all instances in a region, not # availability zone. if profile and alias not in self.opts['profiles'][profile]['provider'].split(':')[0]: continue for vm_name, details in six.iteritems(vms): # XXX: The logic below can be removed once the aws driver # is removed if vm_name not in names: continue elif driver == 'ec2' and 'aws' in handled_drivers and \ 'aws' in matches[handled_drivers['aws']] and \ vm_name in matches[handled_drivers['aws']]['aws']: continue elif driver == 'aws' and 'ec2' in handled_drivers and \ 'ec2' in matches[handled_drivers['ec2']] and \ vm_name in matches[handled_drivers['ec2']]['ec2']: continue if alias not in matches: matches[alias] = {} if driver not in matches[alias]: matches[alias][driver] = {} matches[alias][driver][vm_name] = details return matches def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers def location_list(self, lookup='all'): ''' Return a mapping of all location data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_locations'.format(driver) if fun not in self.clouds: # The capability to gather locations is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the locations information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def size_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_sizes'.format(driver) if fun not in self.clouds: # The capability to gather sizes is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the sizes information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output @staticmethod def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret def do_function(self, prov, func, kwargs): ''' Perform a function against a cloud provider ''' matches = self.lookup_providers(prov) if len(matches) > 1: raise SaltCloudSystemExit( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}'.format( prov, ', '.join([ '{0}:{1}'.format(alias, driver) for (alias, driver) in matches ]) ) ) alias, driver = matches.pop() fun = '{0}.{1}'.format(driver, func) if fun not in self.clouds: raise SaltCloudSystemExit( 'The \'{0}\' cloud provider alias, for the \'{1}\' driver, does ' 'not define the function \'{2}\''.format(alias, driver, func) ) log.debug( 'Trying to execute \'%s\' with the following kwargs: %s', fun, kwargs ) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if kwargs: return { alias: { driver: self.clouds[fun]( call='function', kwargs=kwargs ) } } return { alias: { driver: self.clouds[fun](call='function') } } def __filter_non_working_providers(self): ''' Remove any mis-configured cloud providers from the available listing ''' for alias, drivers in six.iteritems(self.opts['providers'].copy()): for driver in drivers.copy(): fun = '{0}.get_configured_provider'.format(driver) if fun not in self.clouds: # Mis-configured provider that got removed? log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias, could not be loaded. ' 'Please check your provider configuration files and ' 'ensure all required dependencies are installed ' 'for the \'%s\' driver.\n' 'In rare cases, this could indicate the \'%s()\' ' 'function could not be found.\nRemoving \'%s\' from ' 'the available providers list', driver, alias, driver, fun, driver ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if self.clouds[fun]() is False: log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias is not properly ' 'configured. Removing it from the available ' 'providers list.', driver, alias ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias)
saltstack/salt
salt/cloud/__init__.py
Cloud.lookup_profiles
python
def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles
Return a dictionary describing the configured profiles
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L589-L621
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
class Cloud(object): ''' An object for the creation of new VMs ''' def __init__(self, opts): self.opts = opts self.client = CloudClient(opts=self.opts) self.clouds = salt.loader.clouds(self.opts) self.__filter_non_working_providers() self.__cached_provider_queries = {} def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output def get_running_by_names(self, names, query='list_nodes', cached=False, profile=None): if isinstance(names, six.string_types): names = [names] matches = {} handled_drivers = {} mapped_providers = self.map_providers_parallel(query, cached=cached) for alias, drivers in six.iteritems(mapped_providers): for driver, vms in six.iteritems(drivers): if driver not in handled_drivers: handled_drivers[driver] = alias # When a profile is specified, only return an instance # that matches the provider specified in the profile. # This solves the issues when many providers return the # same instance. For example there may be one provider for # each availability zone in amazon in the same region, but # the search returns the same instance for each provider # because amazon returns all instances in a region, not # availability zone. if profile and alias not in self.opts['profiles'][profile]['provider'].split(':')[0]: continue for vm_name, details in six.iteritems(vms): # XXX: The logic below can be removed once the aws driver # is removed if vm_name not in names: continue elif driver == 'ec2' and 'aws' in handled_drivers and \ 'aws' in matches[handled_drivers['aws']] and \ vm_name in matches[handled_drivers['aws']]['aws']: continue elif driver == 'aws' and 'ec2' in handled_drivers and \ 'ec2' in matches[handled_drivers['ec2']] and \ vm_name in matches[handled_drivers['ec2']]['ec2']: continue if alias not in matches: matches[alias] = {} if driver not in matches[alias]: matches[alias][driver] = {} matches[alias][driver][vm_name] = details return matches def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers def location_list(self, lookup='all'): ''' Return a mapping of all location data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_locations'.format(driver) if fun not in self.clouds: # The capability to gather locations is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the locations information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def size_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_sizes'.format(driver) if fun not in self.clouds: # The capability to gather sizes is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the sizes information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output @staticmethod def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret def do_function(self, prov, func, kwargs): ''' Perform a function against a cloud provider ''' matches = self.lookup_providers(prov) if len(matches) > 1: raise SaltCloudSystemExit( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}'.format( prov, ', '.join([ '{0}:{1}'.format(alias, driver) for (alias, driver) in matches ]) ) ) alias, driver = matches.pop() fun = '{0}.{1}'.format(driver, func) if fun not in self.clouds: raise SaltCloudSystemExit( 'The \'{0}\' cloud provider alias, for the \'{1}\' driver, does ' 'not define the function \'{2}\''.format(alias, driver, func) ) log.debug( 'Trying to execute \'%s\' with the following kwargs: %s', fun, kwargs ) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if kwargs: return { alias: { driver: self.clouds[fun]( call='function', kwargs=kwargs ) } } return { alias: { driver: self.clouds[fun](call='function') } } def __filter_non_working_providers(self): ''' Remove any mis-configured cloud providers from the available listing ''' for alias, drivers in six.iteritems(self.opts['providers'].copy()): for driver in drivers.copy(): fun = '{0}.get_configured_provider'.format(driver) if fun not in self.clouds: # Mis-configured provider that got removed? log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias, could not be loaded. ' 'Please check your provider configuration files and ' 'ensure all required dependencies are installed ' 'for the \'%s\' driver.\n' 'In rare cases, this could indicate the \'%s()\' ' 'function could not be found.\nRemoving \'%s\' from ' 'the available providers list', driver, alias, driver, fun, driver ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if self.clouds[fun]() is False: log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias is not properly ' 'configured. Removing it from the available ' 'providers list.', driver, alias ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias)
saltstack/salt
salt/cloud/__init__.py
Cloud.map_providers
python
def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap
Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L623-L657
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
class Cloud(object): ''' An object for the creation of new VMs ''' def __init__(self, opts): self.opts = opts self.client = CloudClient(opts=self.opts) self.clouds = salt.loader.clouds(self.opts) self.__filter_non_working_providers() self.__cached_provider_queries = {} def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output def get_running_by_names(self, names, query='list_nodes', cached=False, profile=None): if isinstance(names, six.string_types): names = [names] matches = {} handled_drivers = {} mapped_providers = self.map_providers_parallel(query, cached=cached) for alias, drivers in six.iteritems(mapped_providers): for driver, vms in six.iteritems(drivers): if driver not in handled_drivers: handled_drivers[driver] = alias # When a profile is specified, only return an instance # that matches the provider specified in the profile. # This solves the issues when many providers return the # same instance. For example there may be one provider for # each availability zone in amazon in the same region, but # the search returns the same instance for each provider # because amazon returns all instances in a region, not # availability zone. if profile and alias not in self.opts['profiles'][profile]['provider'].split(':')[0]: continue for vm_name, details in six.iteritems(vms): # XXX: The logic below can be removed once the aws driver # is removed if vm_name not in names: continue elif driver == 'ec2' and 'aws' in handled_drivers and \ 'aws' in matches[handled_drivers['aws']] and \ vm_name in matches[handled_drivers['aws']]['aws']: continue elif driver == 'aws' and 'ec2' in handled_drivers and \ 'ec2' in matches[handled_drivers['ec2']] and \ vm_name in matches[handled_drivers['ec2']]['ec2']: continue if alias not in matches: matches[alias] = {} if driver not in matches[alias]: matches[alias][driver] = {} matches[alias][driver][vm_name] = details return matches def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers def location_list(self, lookup='all'): ''' Return a mapping of all location data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_locations'.format(driver) if fun not in self.clouds: # The capability to gather locations is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the locations information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def size_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_sizes'.format(driver) if fun not in self.clouds: # The capability to gather sizes is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the sizes information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output @staticmethod def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret def do_function(self, prov, func, kwargs): ''' Perform a function against a cloud provider ''' matches = self.lookup_providers(prov) if len(matches) > 1: raise SaltCloudSystemExit( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}'.format( prov, ', '.join([ '{0}:{1}'.format(alias, driver) for (alias, driver) in matches ]) ) ) alias, driver = matches.pop() fun = '{0}.{1}'.format(driver, func) if fun not in self.clouds: raise SaltCloudSystemExit( 'The \'{0}\' cloud provider alias, for the \'{1}\' driver, does ' 'not define the function \'{2}\''.format(alias, driver, func) ) log.debug( 'Trying to execute \'%s\' with the following kwargs: %s', fun, kwargs ) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if kwargs: return { alias: { driver: self.clouds[fun]( call='function', kwargs=kwargs ) } } return { alias: { driver: self.clouds[fun](call='function') } } def __filter_non_working_providers(self): ''' Remove any mis-configured cloud providers from the available listing ''' for alias, drivers in six.iteritems(self.opts['providers'].copy()): for driver in drivers.copy(): fun = '{0}.get_configured_provider'.format(driver) if fun not in self.clouds: # Mis-configured provider that got removed? log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias, could not be loaded. ' 'Please check your provider configuration files and ' 'ensure all required dependencies are installed ' 'for the \'%s\' driver.\n' 'In rare cases, this could indicate the \'%s()\' ' 'function could not be found.\nRemoving \'%s\' from ' 'the available providers list', driver, alias, driver, fun, driver ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if self.clouds[fun]() is False: log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias is not properly ' 'configured. Removing it from the available ' 'providers list.', driver, alias ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias)
saltstack/salt
salt/cloud/__init__.py
Cloud.map_providers_parallel
python
def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output
Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L659-L715
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def enter_mainloop(target,\n mapped_args=None,\n args=None,\n kwargs=None,\n pool=None,\n pool_size=None,\n callback=None,\n queue=None):\n '''\n Manage a multiprocessing pool\n\n - If the queue does not output anything, the pool runs indefinitely\n\n - If the queue returns KEYBOARDINT or ERROR, this will kill the pool\n totally calling terminate & join and ands with a SaltCloudSystemExit\n exception notifying callers from the abnormal termination\n\n - If the queue returns END or callback is defined and returns True,\n it just join the process and return the data.\n\n target\n the function you want to execute in multiproccessing\n pool\n pool object can be None if you want a default pool, but you ll\n have then to define pool_size instead\n pool_size\n pool size if you did not provide yourself a pool\n callback\n a boolean taking a string in argument which returns True to\n signal that 'target' is finished and we need to join\n the pool\n queue\n A custom multiproccessing queue in case you want to do\n extra stuff and need it later in your program\n args\n positional arguments to call the function with\n if you don't want to use pool.map\n\n mapped_args\n a list of one or more arguments combinations to call the function with\n e.g. (foo, [[1], [2]]) will call::\n\n foo([1])\n foo([2])\n\n kwargs\n kwargs to give to the function in case of process\n\n Attention, the function must have the following signature:\n\n target(queue, *args, **kw)\n\n You may use the 'communicator' decorator to generate such a function\n (see end of this file)\n '''\n if not kwargs:\n kwargs = {}\n if not pool_size:\n pool_size = 1\n if not pool:\n pool = multiprocessing.Pool(pool_size)\n if not queue:\n manager = multiprocessing.Manager()\n queue = manager.Queue()\n\n if mapped_args is not None and not mapped_args:\n msg = (\n 'We are called to asynchronously execute {0}'\n ' but we do no have anything to execute, weird,'\n ' we bail out'.format(target))\n log.error(msg)\n raise SaltCloudSystemExit('Exception caught\\n{0}'.format(msg))\n elif mapped_args is not None:\n iterable = [[queue, [arg], kwargs] for arg in mapped_args]\n ret = pool.map(func=target, iterable=iterable)\n else:\n ret = pool.apply(target, [queue, args, kwargs])\n while True:\n test = queue.get()\n if test in ['ERROR', 'KEYBOARDINT']:\n type_ = queue.get()\n trace = queue.get()\n msg = 'Caught {0}, terminating workers\\n'.format(type_)\n msg += 'TRACE: {0}\\n'.format(trace)\n log.error(msg)\n pool.terminate()\n pool.join()\n raise SaltCloudSystemExit('Exception caught\\n{0}'.format(msg))\n elif test in ['END'] or (callback and callback(test)):\n pool.close()\n pool.join()\n break\n else:\n time.sleep(0.125)\n return ret\n", "def _optimize_providers(self, providers):\n '''\n Return an optimized mapping of available providers\n '''\n new_providers = {}\n provider_by_driver = {}\n\n for alias, driver in six.iteritems(providers):\n for name, data in six.iteritems(driver):\n if name not in provider_by_driver:\n provider_by_driver[name] = {}\n\n provider_by_driver[name][alias] = data\n\n for driver, providers_data in six.iteritems(provider_by_driver):\n fun = '{0}.optimize_providers'.format(driver)\n if fun not in self.clouds:\n log.debug('The \\'%s\\' cloud driver is unable to be optimized.', driver)\n\n for name, prov_data in six.iteritems(providers_data):\n if name not in new_providers:\n new_providers[name] = {}\n new_providers[name][driver] = prov_data\n continue\n\n new_data = self.clouds[fun](providers_data)\n if new_data:\n for name, prov_data in six.iteritems(new_data):\n if name not in new_providers:\n new_providers[name] = {}\n new_providers[name][driver] = prov_data\n\n return new_providers\n" ]
class Cloud(object): ''' An object for the creation of new VMs ''' def __init__(self, opts): self.opts = opts self.client = CloudClient(opts=self.opts) self.clouds = salt.loader.clouds(self.opts) self.__filter_non_working_providers() self.__cached_provider_queries = {} def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap def get_running_by_names(self, names, query='list_nodes', cached=False, profile=None): if isinstance(names, six.string_types): names = [names] matches = {} handled_drivers = {} mapped_providers = self.map_providers_parallel(query, cached=cached) for alias, drivers in six.iteritems(mapped_providers): for driver, vms in six.iteritems(drivers): if driver not in handled_drivers: handled_drivers[driver] = alias # When a profile is specified, only return an instance # that matches the provider specified in the profile. # This solves the issues when many providers return the # same instance. For example there may be one provider for # each availability zone in amazon in the same region, but # the search returns the same instance for each provider # because amazon returns all instances in a region, not # availability zone. if profile and alias not in self.opts['profiles'][profile]['provider'].split(':')[0]: continue for vm_name, details in six.iteritems(vms): # XXX: The logic below can be removed once the aws driver # is removed if vm_name not in names: continue elif driver == 'ec2' and 'aws' in handled_drivers and \ 'aws' in matches[handled_drivers['aws']] and \ vm_name in matches[handled_drivers['aws']]['aws']: continue elif driver == 'aws' and 'ec2' in handled_drivers and \ 'ec2' in matches[handled_drivers['ec2']] and \ vm_name in matches[handled_drivers['ec2']]['ec2']: continue if alias not in matches: matches[alias] = {} if driver not in matches[alias]: matches[alias][driver] = {} matches[alias][driver][vm_name] = details return matches def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers def location_list(self, lookup='all'): ''' Return a mapping of all location data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_locations'.format(driver) if fun not in self.clouds: # The capability to gather locations is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the locations information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def size_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_sizes'.format(driver) if fun not in self.clouds: # The capability to gather sizes is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the sizes information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output @staticmethod def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret def do_function(self, prov, func, kwargs): ''' Perform a function against a cloud provider ''' matches = self.lookup_providers(prov) if len(matches) > 1: raise SaltCloudSystemExit( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}'.format( prov, ', '.join([ '{0}:{1}'.format(alias, driver) for (alias, driver) in matches ]) ) ) alias, driver = matches.pop() fun = '{0}.{1}'.format(driver, func) if fun not in self.clouds: raise SaltCloudSystemExit( 'The \'{0}\' cloud provider alias, for the \'{1}\' driver, does ' 'not define the function \'{2}\''.format(alias, driver, func) ) log.debug( 'Trying to execute \'%s\' with the following kwargs: %s', fun, kwargs ) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if kwargs: return { alias: { driver: self.clouds[fun]( call='function', kwargs=kwargs ) } } return { alias: { driver: self.clouds[fun](call='function') } } def __filter_non_working_providers(self): ''' Remove any mis-configured cloud providers from the available listing ''' for alias, drivers in six.iteritems(self.opts['providers'].copy()): for driver in drivers.copy(): fun = '{0}.get_configured_provider'.format(driver) if fun not in self.clouds: # Mis-configured provider that got removed? log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias, could not be loaded. ' 'Please check your provider configuration files and ' 'ensure all required dependencies are installed ' 'for the \'%s\' driver.\n' 'In rare cases, this could indicate the \'%s()\' ' 'function could not be found.\nRemoving \'%s\' from ' 'the available providers list', driver, alias, driver, fun, driver ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if self.clouds[fun]() is False: log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias is not properly ' 'configured. Removing it from the available ' 'providers list.', driver, alias ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias)
saltstack/salt
salt/cloud/__init__.py
Cloud._optimize_providers
python
def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers
Return an optimized mapping of available providers
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L763-L795
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
class Cloud(object): ''' An object for the creation of new VMs ''' def __init__(self, opts): self.opts = opts self.client = CloudClient(opts=self.opts) self.clouds = salt.loader.clouds(self.opts) self.__filter_non_working_providers() self.__cached_provider_queries = {} def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output def get_running_by_names(self, names, query='list_nodes', cached=False, profile=None): if isinstance(names, six.string_types): names = [names] matches = {} handled_drivers = {} mapped_providers = self.map_providers_parallel(query, cached=cached) for alias, drivers in six.iteritems(mapped_providers): for driver, vms in six.iteritems(drivers): if driver not in handled_drivers: handled_drivers[driver] = alias # When a profile is specified, only return an instance # that matches the provider specified in the profile. # This solves the issues when many providers return the # same instance. For example there may be one provider for # each availability zone in amazon in the same region, but # the search returns the same instance for each provider # because amazon returns all instances in a region, not # availability zone. if profile and alias not in self.opts['profiles'][profile]['provider'].split(':')[0]: continue for vm_name, details in six.iteritems(vms): # XXX: The logic below can be removed once the aws driver # is removed if vm_name not in names: continue elif driver == 'ec2' and 'aws' in handled_drivers and \ 'aws' in matches[handled_drivers['aws']] and \ vm_name in matches[handled_drivers['aws']]['aws']: continue elif driver == 'aws' and 'ec2' in handled_drivers and \ 'ec2' in matches[handled_drivers['ec2']] and \ vm_name in matches[handled_drivers['ec2']]['ec2']: continue if alias not in matches: matches[alias] = {} if driver not in matches[alias]: matches[alias][driver] = {} matches[alias][driver][vm_name] = details return matches def location_list(self, lookup='all'): ''' Return a mapping of all location data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_locations'.format(driver) if fun not in self.clouds: # The capability to gather locations is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the locations information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def size_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_sizes'.format(driver) if fun not in self.clouds: # The capability to gather sizes is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the sizes information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output @staticmethod def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret def do_function(self, prov, func, kwargs): ''' Perform a function against a cloud provider ''' matches = self.lookup_providers(prov) if len(matches) > 1: raise SaltCloudSystemExit( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}'.format( prov, ', '.join([ '{0}:{1}'.format(alias, driver) for (alias, driver) in matches ]) ) ) alias, driver = matches.pop() fun = '{0}.{1}'.format(driver, func) if fun not in self.clouds: raise SaltCloudSystemExit( 'The \'{0}\' cloud provider alias, for the \'{1}\' driver, does ' 'not define the function \'{2}\''.format(alias, driver, func) ) log.debug( 'Trying to execute \'%s\' with the following kwargs: %s', fun, kwargs ) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if kwargs: return { alias: { driver: self.clouds[fun]( call='function', kwargs=kwargs ) } } return { alias: { driver: self.clouds[fun](call='function') } } def __filter_non_working_providers(self): ''' Remove any mis-configured cloud providers from the available listing ''' for alias, drivers in six.iteritems(self.opts['providers'].copy()): for driver in drivers.copy(): fun = '{0}.get_configured_provider'.format(driver) if fun not in self.clouds: # Mis-configured provider that got removed? log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias, could not be loaded. ' 'Please check your provider configuration files and ' 'ensure all required dependencies are installed ' 'for the \'%s\' driver.\n' 'In rare cases, this could indicate the \'%s()\' ' 'function could not be found.\nRemoving \'%s\' from ' 'the available providers list', driver, alias, driver, fun, driver ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if self.clouds[fun]() is False: log.warning( 'The cloud driver, \'%s\', configured under the ' '\'%s\' cloud provider alias is not properly ' 'configured. Removing it from the available ' 'providers list.', driver, alias ) self.opts['providers'][alias].pop(driver) if alias not in self.opts['providers']: continue if not self.opts['providers'][alias]: self.opts['providers'].pop(alias)