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/beacons/diskusage.py
beacon
python
def beacon(config): r''' Monitor the disk usage of the minion Specify thresholds for each disk and only emit a beacon if any of them are exceeded. .. code-block:: yaml beacons: diskusage: - /: 63% - /mnt/nfs: 50% Windows drives must be quoted to avoid yaml syntax errors .. code-block:: yaml beacons: diskusage: - interval: 120 - 'c:\\': 90% - 'd:\\': 50% Regular expressions can be used as mount points. .. code-block:: yaml beacons: diskusage: - '^\/(?!home).*$': 90% - '^[a-zA-Z]:\\$': 50% The first one will match all mounted disks beginning with "/", except /home The second one will match disks from A:\ to Z:\ on a Windows system Note that if a regular expression are evaluated after static mount points, which means that if a regular expression matches another defined mount point, it will override the previously defined threshold. ''' parts = psutil.disk_partitions(all=True) ret = [] for mounts in config: mount = next(iter(mounts)) # Because we're using regular expressions # if our mount doesn't end with a $, insert one. mount_re = mount if not mount.endswith('$'): mount_re = '{0}$'.format(mount) if salt.utils.platform.is_windows(): # mount_re comes in formatted with a $ at the end # can be `C:\\$` or `C:\\\\$` # re string must be like `C:\\\\` regardless of \\ or \\\\ # also, psutil returns uppercase mount_re = re.sub(r':\\\$', r':\\\\', mount_re) mount_re = re.sub(r':\\\\\$', r':\\\\', mount_re) mount_re = mount_re.upper() for part in parts: if re.match(mount_re, part.mountpoint): _mount = part.mountpoint try: _current_usage = psutil.disk_usage(_mount) except OSError: log.warning('%s is not a valid mount point.', _mount) continue current_usage = _current_usage.percent monitor_usage = mounts[mount] if '%' in monitor_usage: monitor_usage = re.sub('%', '', monitor_usage) monitor_usage = float(monitor_usage) if current_usage >= monitor_usage: ret.append({'diskusage': current_usage, 'mount': _mount}) return ret
r''' Monitor the disk usage of the minion Specify thresholds for each disk and only emit a beacon if any of them are exceeded. .. code-block:: yaml beacons: diskusage: - /: 63% - /mnt/nfs: 50% Windows drives must be quoted to avoid yaml syntax errors .. code-block:: yaml beacons: diskusage: - interval: 120 - 'c:\\': 90% - 'd:\\': 50% Regular expressions can be used as mount points. .. code-block:: yaml beacons: diskusage: - '^\/(?!home).*$': 90% - '^[a-zA-Z]:\\$': 50% The first one will match all mounted disks beginning with "/", except /home The second one will match disks from A:\ to Z:\ on a Windows system Note that if a regular expression are evaluated after static mount points, which means that if a regular expression matches another defined mount point, it will override the previously defined threshold.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/diskusage.py#L47-L125
null
# -*- coding: utf-8 -*- ''' Beacon to monitor disk usage. .. versionadded:: 2015.5.0 :depends: python-psutil ''' # Import Python libs from __future__ import absolute_import, unicode_literals import logging import re import salt.utils.platform # Import Third Party Libs try: import psutil HAS_PSUTIL = True except ImportError: HAS_PSUTIL = False log = logging.getLogger(__name__) __virtualname__ = 'diskusage' def __virtual__(): if HAS_PSUTIL is False: return False else: return __virtualname__ def validate(config): ''' Validate the beacon configuration ''' # Configuration for diskusage beacon should be a list of dicts if not isinstance(config, list): return False, ('Configuration for diskusage beacon ' 'must be a list.') return True, 'Valid beacon configuration'
saltstack/salt
salt/tops/saltclass.py
top
python
def top(**kwargs): ''' Compile tops ''' # Node definitions path will be retrieved from args (or set to default), # then added to 'salt_data' dict that is passed to the 'get_pillars' # function. The dictionary contains: # - __opts__ # - __salt__ # - __grains__ # - __pillar__ # - minion_id # - path # # If successful, the function will return a pillar dict for minion_id. # If path has not been set, make a default _opts = __opts__['master_tops']['saltclass'] if 'path' not in _opts: path = '/srv/saltclass' log.warning('path variable unset, using default: %s', path) else: path = _opts['path'] # Create a dict that will contain our salt objects # to send to get_tops function if 'id' not in kwargs['opts']: log.warning('Minion id not found - Returning empty dict') return {} else: minion_id = kwargs['opts']['id'] salt_data = { '__opts__': kwargs['opts'], '__salt__': {}, '__grains__': kwargs['grains'], '__pillar__': {}, 'minion_id': minion_id, 'path': path } return sc.get_tops(minion_id, salt_data)
Compile tops
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tops/saltclass.py#L229-L270
[ "def get_tops(minion_id, salt_data):\n # Get 2 dicts and 2 lists\n # expanded_classes: Full list of expanded dicts\n # pillars_dict: dict containing merged pillars in order\n # classes_list: All classes processed in order\n # states_list: All states listed in order\n (expanded_classes,\n pillars_dict,\n classes_list,\n states_list) = expanded_dict_from_minion(minion_id, salt_data)\n\n # Retrieve environment\n environment = get_env_from_dict(expanded_classes)\n\n # Build final top dict\n tops_dict = {}\n tops_dict[environment] = states_list\n\n return tops_dict\n" ]
# -*- coding: utf-8 -*- r''' Saltclass Configuration ======================= .. code-block:: yaml master_tops: saltclass: path: /srv/saltclass Description =========== This module clones the behaviour of reclass (http://reclass.pantsfullofunix.net/), without the need of an external app, and add several features to improve flexibility. Saltclass lets you define your nodes from simple ``yaml`` files (``.yml``) through hierarchical class inheritance with the possibility to override pillars down the tree. Features ======== - Define your nodes through hierarchical class inheritance - Reuse your reclass datas with minimal modifications - applications => states - parameters => pillars - Use Jinja templating in your yaml definitions - Access to the following Salt objects in Jinja - ``__opts__`` - ``__salt__`` - ``__grains__`` - ``__pillars__`` - ``minion_id`` - Chose how to merge or override your lists using ^ character (see examples) - Expand variables ${} with possibility to escape them if needed \${} (see examples) - Ignores missing node/class and will simply return empty without breaking the pillar module completely - will be logged An example subset of datas is available here: http://git.mauras.ch/salt/saltclass/src/master/examples ========================== =========== Terms usable in yaml files Description ========================== =========== classes A list of classes that will be processed in order states A list of states that will be returned by master_tops function pillars A yaml dictionnary that will be returned by the ext_pillar function environment Node saltenv that will be used by master_tops ========================== =========== A class consists of: - zero or more parent classes - zero or more states - any number of pillars A child class can override pillars from a parent class. A node definition is a class in itself with an added ``environment`` parameter for ``saltenv`` definition. Class names =========== Class names mimic salt way of defining states and pillar files. This means that ``default.users`` class name will correspond to one of these: - ``<saltclass_path>/classes/default/users.yml`` - ``<saltclass_path>/classes/default/users/init.yml`` Saltclass file hierachy ======================= A saltclass tree would look like this: .. code-block:: text <saltclass_path> β”œβ”€β”€ classes β”‚ β”œβ”€β”€ app β”‚ β”‚ β”œβ”€β”€ borgbackup.yml β”‚ β”‚ └── ssh β”‚ β”‚ └── server.yml β”‚ β”œβ”€β”€ default β”‚ β”‚ β”œβ”€β”€ init.yml β”‚ β”‚ β”œβ”€β”€ motd.yml β”‚ β”‚ └── users.yml β”‚ β”œβ”€β”€ roles β”‚ β”‚ β”œβ”€β”€ app.yml β”‚ β”‚ └── nginx β”‚ β”‚ β”œβ”€β”€ init.yml β”‚ β”‚ └── server.yml β”‚ └── subsidiaries β”‚ β”œβ”€β”€ gnv.yml β”‚ β”œβ”€β”€ qls.yml β”‚ └── zrh.yml └── nodes β”œβ”€β”€ geneva β”‚ └── gnv.node1.yml β”œβ”€β”€ lausanne β”‚ β”œβ”€β”€ qls.node1.yml β”‚ └── qls.node2.yml β”œβ”€β”€ node127.yml └── zurich β”œβ”€β”€ zrh.node1.yml β”œβ”€β”€ zrh.node2.yml └── zrh.node3.yml Saltclass Examples ================== ``<saltclass_path>/nodes/lausanne/qls.node1.yml`` .. code-block:: jinja environment: base classes: {% for class in ['default'] %} - {{ class }} {% endfor %} - subsidiaries.{{ __grains__['id'].split('.')[0] }} ``<saltclass_path>/classes/default/init.yml`` .. code-block:: yaml classes: - default.users - default.motd states: - openssh pillars: default: network: dns: srv1: 192.168.0.1 srv2: 192.168.0.2 domain: example.com ntp: srv1: 192.168.10.10 srv2: 192.168.10.20 ``<saltclass_path>/classes/subsidiaries/gnv.yml`` .. code-block:: yaml pillars: default: network: sub: Geneva dns: srv1: 10.20.0.1 srv2: 10.20.0.2 srv3: 192.168.1.1 domain: gnv.example.com users: adm1: uid: 1210 gid: 1210 gecos: 'Super user admin1' homedir: /srv/app/adm1 adm3: uid: 1203 gid: 1203 gecos: 'Super user adm Variable expansions =================== Escaped variables are rendered as is: ``${test}`` Missing variables are rendered as is: ``${net:dns:srv2}`` .. code-block:: yaml pillars: app: config: dns: srv1: ${default:network:dns:srv1} srv2: ${net:dns:srv2} uri: https://application.domain/call?\${test} prod_parameters: - p1 - p2 - p3 pkg: - app-core - app-backend List override ============= Not using ``^`` as the first entry will simply merge the lists .. code-block:: yaml pillars: app: pkg: - ^ - app-frontend .. note:: **Known limitation** Currently you can't have both a variable and an escaped variable in the same string as the escaped one will not be correctly rendered - '\${xx}' will stay as is instead of being rendered as '${xx}' ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import salt.utils.saltclass as sc log = logging.getLogger(__name__) def __virtual__(): ''' Only run if properly configured ''' if __opts__['master_tops'].get('saltclass'): return True return False
saltstack/salt
salt/proxy/cisconso.py
ping
python
def ping(): ''' Check to see if the host is responding. Returns False if the host didn't respond, True otherwise. CLI Example: .. code-block:: bash salt cisco-nso test.ping ''' try: client = _get_client() client.info() except SaltSystemExit as err: log.warning(err) return False return True
Check to see if the host is responding. Returns False if the host didn't respond, True otherwise. CLI Example: .. code-block:: bash salt cisco-nso test.ping
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cisconso.py#L235-L253
[ "def _get_client():\n return NSOClient(\n host=DETAILS['host'],\n username=DETAILS['username'],\n password=DETAILS['password'],\n port=DETAILS['port'],\n ssl=DETAILS['use_ssl'])\n" ]
# -*- coding: utf-8 -*- ''' Proxy Minion interface module for managing (practically) any network device with Cisco Network Services Orchestrator (Cisco NSO). Cisco NSO uses a series of remote polling agents, APIs and SSH commands to fetch network configuration and represent it in a data model. PyNSO, the Python module used by this proxy minion does the task of converting native Python dictionaries into NETCONF/YANG syntax that the REST API for Cisco NSO can then use to set the configuration of the target network device. Supported devices: - A10 AX Series - Arista 7150 Series - Ciena 3000, 5000, ESM - H3c S5800 Series - Overture 1400, 2200, 5000, 5100, 6000 - Accedian MetroNID - Avaya ERS 4000, SR8000, VSP 9000 - Cisco: APIC-DC, ASA, IOS, IOS XE, IOS XR, er, ME-4600, NX OS, Prime Network Registrar, Quantum, StarOS, UCS ManagWSA - Huawei: NE40E, quidway series, Enterprise Network Simulation Framework - PaloAlto PA-2000, PA-3000, Virtualized Firewalls - Adtran 900 Series - Brocade ADX, MLX, Netiron, Vyatta - Dell Force 10 Networking S-Series - Infinera DTN-X Multi-Terabit Packet Optical Network Platform - Pulsecom SuperG - Adva 150CC Series - CableLabs Converged Cable Access Platform - Ericsson EFN324 Series, SE family - Juniper: Contrail, EX, M, MX, QFX, SRX, Virtual SRX - Quagga Routing Software - Affirmed Networks - Citrix Netscaler - F5 BIG-IP - NEC iPasolink - Riverbed Steelhead Series - Alcatel-Lucent 7XXX, SAM - Clavister - Fortinet - Nominum DCS - Sonus SBC 5000 Series - Allied Telesys - Open vSwitch .. versionadded:: 2016.11.0 :codeauthor: `Anthony Shaw <anthony.shaw@dimensiondata.com>` This proxy minion enables a consistent interface to fetch, control and maintain the configuration of network devices via a NETCONF-compliant control plane. Cisco Network Services Orchestrator. More in-depth conceptual reading on Proxy Minions can be found in the :ref:`Proxy Minion <proxy-minion>` section of Salt's documentation. Dependencies ============ - pynso Python module PyNSO ------- PyNSO can be installed via pip: .. code-block:: bash pip install pynso Configuration ============= To use this integration proxy module, please configure the following: Pillar ------ Proxy minions get their configuration from Salt's Pillar. Every proxy must have a stanza in Pillar and a reference in the Pillar top-file that matches the ID. At a minimum for communication with the NSO host, the pillar should look like this: .. code-block:: yaml proxy: proxytype: cisconso host: <ip or dns name of host> port: 8080 use_ssl: false username: <username> password: password proxytype ^^^^^^^^^ The ``proxytype`` key and value pair is critical, as it tells Salt which interface to load from the ``proxy`` directory in Salt's install hierarchy, or from ``/srv/salt/_proxy`` on the Salt Master (if you have created your own proxy module, for example). To use this Cisco NSO Proxy Module, set this to ``cisconso``. host ^^^^ The location, or IP/dns, of the Cisco NSO API host. Required. username ^^^^^^^^ The username used to login to the Cisco NSO host, such as ``admin``. Required. passwords ^^^^^^^^^ The password for the given user. Required. use_ssl ^^^^^^^^ Whether to use HTTPS messaging to speak to the API. port ^^^^ The port that the Cisco NSO API is running on, 8080 by default Salt Proxy ---------- After your pillar is in place, you can test the proxy. The proxy can run on any machine that has network connectivity to your Salt Master and to the Cisco NSO host in question. SaltStack recommends that the machine running the salt-proxy process also run a regular minion, though it is not strictly necessary. On the machine that will run the proxy, make sure there is an ``/etc/salt/proxy`` file with at least the following in it: .. code-block:: yaml master: <ip or hostname of salt-master> You can then start the salt-proxy process with: .. code-block:: bash salt-proxy --proxyid <id you want to give the host> You may want to add ``-l debug`` to run the above in the foreground in debug mode just to make sure everything is OK. Next, accept the key for the proxy on your salt-master, just like you would for a regular minion: .. code-block:: bash salt-key -a <id you gave the cisconso host> You can confirm that the pillar data is in place for the proxy: .. code-block:: bash salt <id> pillar.items And now you should be able to ping the Cisco NSO host to make sure it is responding: .. code-block:: bash salt <id> test.ping ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs from salt.exceptions import SaltSystemExit # This must be present or the Salt loader won't load this module. __proxyenabled__ = ['cisconso'] try: from pynso.client import NSOClient from pynso.datastores import DatastoreType HAS_PYNSO_LIBS = True except ImportError: HAS_PYNSO_LIBS = False # Variables are scoped to this module so we can have persistent data # across calls to fns in here. GRAINS_CACHE = {} DETAILS = {} # Set up logging log = logging.getLogger(__file__) # Define the module's virtual name __virtualname__ = 'cisconso' def __virtual__(): return HAS_PYNSO_LIBS def init(opts): # Set configuration details DETAILS['host'] = opts['proxy'].get('host') DETAILS['username'] = opts['proxy'].get('username') DETAILS['password'] = opts['proxy'].get('password') DETAILS['use_ssl'] = bool(opts['proxy'].get('use_ssl')) DETAILS['port'] = int(opts['proxy'].get('port')) def grains(): ''' Get the grains from the proxy device. ''' if not GRAINS_CACHE: return _grains() return GRAINS_CACHE def _get_client(): return NSOClient( host=DETAILS['host'], username=DETAILS['username'], password=DETAILS['password'], port=DETAILS['port'], ssl=DETAILS['use_ssl']) def shutdown(): ''' Shutdown the connection to the proxy device. For this proxy, shutdown is a no-op. ''' log.debug('Cisco NSO proxy shutdown() called...') def get_data(datastore, path): ''' Get the configuration of the device tree at the given path :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path, a list of element names in order, comma separated :type path: ``list`` of ``str`` OR ``tuple`` :return: The network configuration at that tree :rtype: ``dict`` .. code-block:: bash salt cisco-nso cisconso.get_data devices ''' client = _get_client() return client.get_datastore_data(datastore, path) def set_data_value(datastore, path, data): ''' Get a data entry in a datastore :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, comma separated :type path: ``list`` of ``str`` OR ``tuple`` :param data: The new value at the given path :type data: ``dict`` :rtype: ``bool`` :return: ``True`` if successful, otherwise error. ''' client = _get_client() return client.set_data_value(datastore, path, data) def get_rollbacks(): ''' Get a list of stored configuration rollbacks ''' return _get_client().get_rollbacks() def get_rollback(name): ''' Get the backup of stored a configuration rollback :param name: Typically an ID of the backup :type name: ``str`` :rtype: ``str`` :return: the contents of the rollback snapshot ''' return _get_client().get_rollback(name) def apply_rollback(datastore, name): ''' Apply a system rollback :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param name: an ID of the rollback to restore :type name: ``str`` ''' return _get_client().apply_rollback(datastore, name) def _grains(): ''' Helper function to the grains from the proxied devices. ''' client = _get_client() # This is a collection of the configuration of all running devices under NSO ret = client.get_datastore(DatastoreType.RUNNING) GRAINS_CACHE.update(ret) return GRAINS_CACHE
saltstack/salt
salt/proxy/cisconso.py
set_data_value
python
def set_data_value(datastore, path, data): ''' Get a data entry in a datastore :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, comma separated :type path: ``list`` of ``str`` OR ``tuple`` :param data: The new value at the given path :type data: ``dict`` :rtype: ``bool`` :return: ``True`` if successful, otherwise error. ''' client = _get_client() return client.set_data_value(datastore, path, data)
Get a data entry in a datastore :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, comma separated :type path: ``list`` of ``str`` OR ``tuple`` :param data: The new value at the given path :type data: ``dict`` :rtype: ``bool`` :return: ``True`` if successful, otherwise error.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cisconso.py#L287-L306
[ "def _get_client():\n return NSOClient(\n host=DETAILS['host'],\n username=DETAILS['username'],\n password=DETAILS['password'],\n port=DETAILS['port'],\n ssl=DETAILS['use_ssl'])\n" ]
# -*- coding: utf-8 -*- ''' Proxy Minion interface module for managing (practically) any network device with Cisco Network Services Orchestrator (Cisco NSO). Cisco NSO uses a series of remote polling agents, APIs and SSH commands to fetch network configuration and represent it in a data model. PyNSO, the Python module used by this proxy minion does the task of converting native Python dictionaries into NETCONF/YANG syntax that the REST API for Cisco NSO can then use to set the configuration of the target network device. Supported devices: - A10 AX Series - Arista 7150 Series - Ciena 3000, 5000, ESM - H3c S5800 Series - Overture 1400, 2200, 5000, 5100, 6000 - Accedian MetroNID - Avaya ERS 4000, SR8000, VSP 9000 - Cisco: APIC-DC, ASA, IOS, IOS XE, IOS XR, er, ME-4600, NX OS, Prime Network Registrar, Quantum, StarOS, UCS ManagWSA - Huawei: NE40E, quidway series, Enterprise Network Simulation Framework - PaloAlto PA-2000, PA-3000, Virtualized Firewalls - Adtran 900 Series - Brocade ADX, MLX, Netiron, Vyatta - Dell Force 10 Networking S-Series - Infinera DTN-X Multi-Terabit Packet Optical Network Platform - Pulsecom SuperG - Adva 150CC Series - CableLabs Converged Cable Access Platform - Ericsson EFN324 Series, SE family - Juniper: Contrail, EX, M, MX, QFX, SRX, Virtual SRX - Quagga Routing Software - Affirmed Networks - Citrix Netscaler - F5 BIG-IP - NEC iPasolink - Riverbed Steelhead Series - Alcatel-Lucent 7XXX, SAM - Clavister - Fortinet - Nominum DCS - Sonus SBC 5000 Series - Allied Telesys - Open vSwitch .. versionadded:: 2016.11.0 :codeauthor: `Anthony Shaw <anthony.shaw@dimensiondata.com>` This proxy minion enables a consistent interface to fetch, control and maintain the configuration of network devices via a NETCONF-compliant control plane. Cisco Network Services Orchestrator. More in-depth conceptual reading on Proxy Minions can be found in the :ref:`Proxy Minion <proxy-minion>` section of Salt's documentation. Dependencies ============ - pynso Python module PyNSO ------- PyNSO can be installed via pip: .. code-block:: bash pip install pynso Configuration ============= To use this integration proxy module, please configure the following: Pillar ------ Proxy minions get their configuration from Salt's Pillar. Every proxy must have a stanza in Pillar and a reference in the Pillar top-file that matches the ID. At a minimum for communication with the NSO host, the pillar should look like this: .. code-block:: yaml proxy: proxytype: cisconso host: <ip or dns name of host> port: 8080 use_ssl: false username: <username> password: password proxytype ^^^^^^^^^ The ``proxytype`` key and value pair is critical, as it tells Salt which interface to load from the ``proxy`` directory in Salt's install hierarchy, or from ``/srv/salt/_proxy`` on the Salt Master (if you have created your own proxy module, for example). To use this Cisco NSO Proxy Module, set this to ``cisconso``. host ^^^^ The location, or IP/dns, of the Cisco NSO API host. Required. username ^^^^^^^^ The username used to login to the Cisco NSO host, such as ``admin``. Required. passwords ^^^^^^^^^ The password for the given user. Required. use_ssl ^^^^^^^^ Whether to use HTTPS messaging to speak to the API. port ^^^^ The port that the Cisco NSO API is running on, 8080 by default Salt Proxy ---------- After your pillar is in place, you can test the proxy. The proxy can run on any machine that has network connectivity to your Salt Master and to the Cisco NSO host in question. SaltStack recommends that the machine running the salt-proxy process also run a regular minion, though it is not strictly necessary. On the machine that will run the proxy, make sure there is an ``/etc/salt/proxy`` file with at least the following in it: .. code-block:: yaml master: <ip or hostname of salt-master> You can then start the salt-proxy process with: .. code-block:: bash salt-proxy --proxyid <id you want to give the host> You may want to add ``-l debug`` to run the above in the foreground in debug mode just to make sure everything is OK. Next, accept the key for the proxy on your salt-master, just like you would for a regular minion: .. code-block:: bash salt-key -a <id you gave the cisconso host> You can confirm that the pillar data is in place for the proxy: .. code-block:: bash salt <id> pillar.items And now you should be able to ping the Cisco NSO host to make sure it is responding: .. code-block:: bash salt <id> test.ping ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs from salt.exceptions import SaltSystemExit # This must be present or the Salt loader won't load this module. __proxyenabled__ = ['cisconso'] try: from pynso.client import NSOClient from pynso.datastores import DatastoreType HAS_PYNSO_LIBS = True except ImportError: HAS_PYNSO_LIBS = False # Variables are scoped to this module so we can have persistent data # across calls to fns in here. GRAINS_CACHE = {} DETAILS = {} # Set up logging log = logging.getLogger(__file__) # Define the module's virtual name __virtualname__ = 'cisconso' def __virtual__(): return HAS_PYNSO_LIBS def init(opts): # Set configuration details DETAILS['host'] = opts['proxy'].get('host') DETAILS['username'] = opts['proxy'].get('username') DETAILS['password'] = opts['proxy'].get('password') DETAILS['use_ssl'] = bool(opts['proxy'].get('use_ssl')) DETAILS['port'] = int(opts['proxy'].get('port')) def grains(): ''' Get the grains from the proxy device. ''' if not GRAINS_CACHE: return _grains() return GRAINS_CACHE def _get_client(): return NSOClient( host=DETAILS['host'], username=DETAILS['username'], password=DETAILS['password'], port=DETAILS['port'], ssl=DETAILS['use_ssl']) def ping(): ''' Check to see if the host is responding. Returns False if the host didn't respond, True otherwise. CLI Example: .. code-block:: bash salt cisco-nso test.ping ''' try: client = _get_client() client.info() except SaltSystemExit as err: log.warning(err) return False return True def shutdown(): ''' Shutdown the connection to the proxy device. For this proxy, shutdown is a no-op. ''' log.debug('Cisco NSO proxy shutdown() called...') def get_data(datastore, path): ''' Get the configuration of the device tree at the given path :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path, a list of element names in order, comma separated :type path: ``list`` of ``str`` OR ``tuple`` :return: The network configuration at that tree :rtype: ``dict`` .. code-block:: bash salt cisco-nso cisconso.get_data devices ''' client = _get_client() return client.get_datastore_data(datastore, path) def get_rollbacks(): ''' Get a list of stored configuration rollbacks ''' return _get_client().get_rollbacks() def get_rollback(name): ''' Get the backup of stored a configuration rollback :param name: Typically an ID of the backup :type name: ``str`` :rtype: ``str`` :return: the contents of the rollback snapshot ''' return _get_client().get_rollback(name) def apply_rollback(datastore, name): ''' Apply a system rollback :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param name: an ID of the rollback to restore :type name: ``str`` ''' return _get_client().apply_rollback(datastore, name) def _grains(): ''' Helper function to the grains from the proxied devices. ''' client = _get_client() # This is a collection of the configuration of all running devices under NSO ret = client.get_datastore(DatastoreType.RUNNING) GRAINS_CACHE.update(ret) return GRAINS_CACHE
saltstack/salt
salt/proxy/cisconso.py
_grains
python
def _grains(): ''' Helper function to the grains from the proxied devices. ''' client = _get_client() # This is a collection of the configuration of all running devices under NSO ret = client.get_datastore(DatastoreType.RUNNING) GRAINS_CACHE.update(ret) return GRAINS_CACHE
Helper function to the grains from the proxied devices.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cisconso.py#L343-L351
[ "def _get_client():\n return NSOClient(\n host=DETAILS['host'],\n username=DETAILS['username'],\n password=DETAILS['password'],\n port=DETAILS['port'],\n ssl=DETAILS['use_ssl'])\n" ]
# -*- coding: utf-8 -*- ''' Proxy Minion interface module for managing (practically) any network device with Cisco Network Services Orchestrator (Cisco NSO). Cisco NSO uses a series of remote polling agents, APIs and SSH commands to fetch network configuration and represent it in a data model. PyNSO, the Python module used by this proxy minion does the task of converting native Python dictionaries into NETCONF/YANG syntax that the REST API for Cisco NSO can then use to set the configuration of the target network device. Supported devices: - A10 AX Series - Arista 7150 Series - Ciena 3000, 5000, ESM - H3c S5800 Series - Overture 1400, 2200, 5000, 5100, 6000 - Accedian MetroNID - Avaya ERS 4000, SR8000, VSP 9000 - Cisco: APIC-DC, ASA, IOS, IOS XE, IOS XR, er, ME-4600, NX OS, Prime Network Registrar, Quantum, StarOS, UCS ManagWSA - Huawei: NE40E, quidway series, Enterprise Network Simulation Framework - PaloAlto PA-2000, PA-3000, Virtualized Firewalls - Adtran 900 Series - Brocade ADX, MLX, Netiron, Vyatta - Dell Force 10 Networking S-Series - Infinera DTN-X Multi-Terabit Packet Optical Network Platform - Pulsecom SuperG - Adva 150CC Series - CableLabs Converged Cable Access Platform - Ericsson EFN324 Series, SE family - Juniper: Contrail, EX, M, MX, QFX, SRX, Virtual SRX - Quagga Routing Software - Affirmed Networks - Citrix Netscaler - F5 BIG-IP - NEC iPasolink - Riverbed Steelhead Series - Alcatel-Lucent 7XXX, SAM - Clavister - Fortinet - Nominum DCS - Sonus SBC 5000 Series - Allied Telesys - Open vSwitch .. versionadded:: 2016.11.0 :codeauthor: `Anthony Shaw <anthony.shaw@dimensiondata.com>` This proxy minion enables a consistent interface to fetch, control and maintain the configuration of network devices via a NETCONF-compliant control plane. Cisco Network Services Orchestrator. More in-depth conceptual reading on Proxy Minions can be found in the :ref:`Proxy Minion <proxy-minion>` section of Salt's documentation. Dependencies ============ - pynso Python module PyNSO ------- PyNSO can be installed via pip: .. code-block:: bash pip install pynso Configuration ============= To use this integration proxy module, please configure the following: Pillar ------ Proxy minions get their configuration from Salt's Pillar. Every proxy must have a stanza in Pillar and a reference in the Pillar top-file that matches the ID. At a minimum for communication with the NSO host, the pillar should look like this: .. code-block:: yaml proxy: proxytype: cisconso host: <ip or dns name of host> port: 8080 use_ssl: false username: <username> password: password proxytype ^^^^^^^^^ The ``proxytype`` key and value pair is critical, as it tells Salt which interface to load from the ``proxy`` directory in Salt's install hierarchy, or from ``/srv/salt/_proxy`` on the Salt Master (if you have created your own proxy module, for example). To use this Cisco NSO Proxy Module, set this to ``cisconso``. host ^^^^ The location, or IP/dns, of the Cisco NSO API host. Required. username ^^^^^^^^ The username used to login to the Cisco NSO host, such as ``admin``. Required. passwords ^^^^^^^^^ The password for the given user. Required. use_ssl ^^^^^^^^ Whether to use HTTPS messaging to speak to the API. port ^^^^ The port that the Cisco NSO API is running on, 8080 by default Salt Proxy ---------- After your pillar is in place, you can test the proxy. The proxy can run on any machine that has network connectivity to your Salt Master and to the Cisco NSO host in question. SaltStack recommends that the machine running the salt-proxy process also run a regular minion, though it is not strictly necessary. On the machine that will run the proxy, make sure there is an ``/etc/salt/proxy`` file with at least the following in it: .. code-block:: yaml master: <ip or hostname of salt-master> You can then start the salt-proxy process with: .. code-block:: bash salt-proxy --proxyid <id you want to give the host> You may want to add ``-l debug`` to run the above in the foreground in debug mode just to make sure everything is OK. Next, accept the key for the proxy on your salt-master, just like you would for a regular minion: .. code-block:: bash salt-key -a <id you gave the cisconso host> You can confirm that the pillar data is in place for the proxy: .. code-block:: bash salt <id> pillar.items And now you should be able to ping the Cisco NSO host to make sure it is responding: .. code-block:: bash salt <id> test.ping ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs from salt.exceptions import SaltSystemExit # This must be present or the Salt loader won't load this module. __proxyenabled__ = ['cisconso'] try: from pynso.client import NSOClient from pynso.datastores import DatastoreType HAS_PYNSO_LIBS = True except ImportError: HAS_PYNSO_LIBS = False # Variables are scoped to this module so we can have persistent data # across calls to fns in here. GRAINS_CACHE = {} DETAILS = {} # Set up logging log = logging.getLogger(__file__) # Define the module's virtual name __virtualname__ = 'cisconso' def __virtual__(): return HAS_PYNSO_LIBS def init(opts): # Set configuration details DETAILS['host'] = opts['proxy'].get('host') DETAILS['username'] = opts['proxy'].get('username') DETAILS['password'] = opts['proxy'].get('password') DETAILS['use_ssl'] = bool(opts['proxy'].get('use_ssl')) DETAILS['port'] = int(opts['proxy'].get('port')) def grains(): ''' Get the grains from the proxy device. ''' if not GRAINS_CACHE: return _grains() return GRAINS_CACHE def _get_client(): return NSOClient( host=DETAILS['host'], username=DETAILS['username'], password=DETAILS['password'], port=DETAILS['port'], ssl=DETAILS['use_ssl']) def ping(): ''' Check to see if the host is responding. Returns False if the host didn't respond, True otherwise. CLI Example: .. code-block:: bash salt cisco-nso test.ping ''' try: client = _get_client() client.info() except SaltSystemExit as err: log.warning(err) return False return True def shutdown(): ''' Shutdown the connection to the proxy device. For this proxy, shutdown is a no-op. ''' log.debug('Cisco NSO proxy shutdown() called...') def get_data(datastore, path): ''' Get the configuration of the device tree at the given path :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path, a list of element names in order, comma separated :type path: ``list`` of ``str`` OR ``tuple`` :return: The network configuration at that tree :rtype: ``dict`` .. code-block:: bash salt cisco-nso cisconso.get_data devices ''' client = _get_client() return client.get_datastore_data(datastore, path) def set_data_value(datastore, path, data): ''' Get a data entry in a datastore :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, comma separated :type path: ``list`` of ``str`` OR ``tuple`` :param data: The new value at the given path :type data: ``dict`` :rtype: ``bool`` :return: ``True`` if successful, otherwise error. ''' client = _get_client() return client.set_data_value(datastore, path, data) def get_rollbacks(): ''' Get a list of stored configuration rollbacks ''' return _get_client().get_rollbacks() def get_rollback(name): ''' Get the backup of stored a configuration rollback :param name: Typically an ID of the backup :type name: ``str`` :rtype: ``str`` :return: the contents of the rollback snapshot ''' return _get_client().get_rollback(name) def apply_rollback(datastore, name): ''' Apply a system rollback :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param name: an ID of the rollback to restore :type name: ``str`` ''' return _get_client().apply_rollback(datastore, name)
saltstack/salt
salt/modules/mac_softwareupdate.py
_get_available
python
def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart
Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... }
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L34-L85
[ "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 execute_return_result(cmd):\n '''\n Executes the passed command. Returns the standard out if successful\n\n :param str cmd: The command to run\n\n :return: The standard out of the command if successful, otherwise returns\n an error\n :rtype: str\n\n :raises: Error if command fails or is not supported\n '''\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return ret['stdout']\n", "_get = lambda l, k: l[keys.index(k)]\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored() def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out) def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on' def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name) def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads() def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads() def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default' def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
saltstack/salt
salt/modules/mac_softwareupdate.py
ignore
python
def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored()
Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L108-L133
[ "def execute_return_success(cmd):\n '''\n Executes the passed command. Returns True if successful\n\n :param str cmd: The command to run\n\n :return: True if successful, otherwise False\n :rtype: bool\n\n :raises: Error if command fails or is not supported\n '''\n\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return True\n", "def list_ignored():\n '''\n List all updates that have been ignored. Ignored updates are shown\n without the '-' and version number at the end, this is how the\n softwareupdate command works.\n\n :return: The list of ignored updates\n :rtype: list\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' softwareupdate.list_ignored\n '''\n cmd = ['softwareupdate', '--list', '--ignore']\n out = salt.utils.mac_utils.execute_return_result(cmd)\n\n # rep parses lines that look like the following:\n # \"Safari6.1.2MountainLion-6.1.2\",\n # or:\n # Safari6.1.2MountainLion-6.1.2\n rexp = re.compile('(?m)^ [\"]?'\n r'([^,|\\s].*[^\"|\\n|,])[,|\"]?')\n\n return rexp.findall(out)\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out) def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on' def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name) def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads() def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads() def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default' def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
saltstack/salt
salt/modules/mac_softwareupdate.py
list_ignored
python
def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out)
List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L136-L161
[ "def execute_return_result(cmd):\n '''\n Executes the passed command. Returns the standard out if successful\n\n :param str cmd: The command to run\n\n :return: The standard out of the command if successful, otherwise returns\n an error\n :rtype: str\n\n :raises: Error if command fails or is not supported\n '''\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return ret['stdout']\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored() def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on' def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name) def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads() def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads() def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default' def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
saltstack/salt
salt/modules/mac_softwareupdate.py
schedule_enabled
python
def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on'
Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L184-L203
[ "def execute_return_result(cmd):\n '''\n Executes the passed command. Returns the standard out if successful\n\n :param str cmd: The command to run\n\n :return: The standard out of the command if successful, otherwise returns\n an error\n :rtype: str\n\n :raises: Error if command fails or is not supported\n '''\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return ret['stdout']\n", "def validate_enabled(enabled):\n '''\n Helper function to validate the enabled parameter. Boolean values are\n converted to \"on\" and \"off\". String values are checked to make sure they are\n either \"on\" or \"off\"/\"yes\" or \"no\". Integer ``0`` will return \"off\". All\n other integers will return \"on\"\n\n :param enabled: Enabled can be boolean True or False, Integers, or string\n values \"on\" and \"off\"/\"yes\" and \"no\".\n :type: str, int, bool\n\n :return: \"on\" or \"off\" or errors\n :rtype: str\n '''\n if isinstance(enabled, six.string_types):\n if enabled.lower() not in ['on', 'off', 'yes', 'no']:\n msg = '\\nMac Power: Invalid String Value for Enabled.\\n' \\\n 'String values must be \\'on\\' or \\'off\\'/\\'yes\\' or \\'no\\'.\\n' \\\n 'Passed: {0}'.format(enabled)\n raise SaltInvocationError(msg)\n\n return 'on' if enabled.lower() in ['on', 'yes'] else 'off'\n\n return 'on' if bool(enabled) else 'off'\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored() def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out) def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name) def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads() def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads() def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default' def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
saltstack/salt
salt/modules/mac_softwareupdate.py
schedule_enable
python
def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status
Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L206-L232
[ "def execute_return_success(cmd):\n '''\n Executes the passed command. Returns True if successful\n\n :param str cmd: The command to run\n\n :return: True if successful, otherwise False\n :rtype: bool\n\n :raises: Error if command fails or is not supported\n '''\n\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return True\n", "def validate_enabled(enabled):\n '''\n Helper function to validate the enabled parameter. Boolean values are\n converted to \"on\" and \"off\". String values are checked to make sure they are\n either \"on\" or \"off\"/\"yes\" or \"no\". Integer ``0`` will return \"off\". All\n other integers will return \"on\"\n\n :param enabled: Enabled can be boolean True or False, Integers, or string\n values \"on\" and \"off\"/\"yes\" and \"no\".\n :type: str, int, bool\n\n :return: \"on\" or \"off\" or errors\n :rtype: str\n '''\n if isinstance(enabled, six.string_types):\n if enabled.lower() not in ['on', 'off', 'yes', 'no']:\n msg = '\\nMac Power: Invalid String Value for Enabled.\\n' \\\n 'String values must be \\'on\\' or \\'off\\'/\\'yes\\' or \\'no\\'.\\n' \\\n 'Passed: {0}'.format(enabled)\n raise SaltInvocationError(msg)\n\n return 'on' if enabled.lower() in ['on', 'yes'] else 'off'\n\n return 'on' if bool(enabled) else 'off'\n", "def schedule_enabled():\n '''\n Check the status of automatic update scheduling.\n\n :return: True if scheduling is enabled, False if disabled\n\n :rtype: bool\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' softwareupdate.schedule_enabled\n '''\n cmd = ['softwareupdate', '--schedule']\n ret = salt.utils.mac_utils.execute_return_result(cmd)\n\n enabled = ret.split()[-1]\n\n return salt.utils.mac_utils.validate_enabled(enabled) == 'on'\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored() def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out) def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on' def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name) def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads() def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads() def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default' def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
saltstack/salt
salt/modules/mac_softwareupdate.py
update_all
python
def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret
Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L235-L273
[ "def execute_return_success(cmd):\n '''\n Executes the passed command. Returns True if successful\n\n :param str cmd: The command to run\n\n :return: True if successful, otherwise False\n :rtype: bool\n\n :raises: Error if command fails or is not supported\n '''\n\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return True\n", "def _get_available(recommended=False, restart=False):\n '''\n Utility function to get all available update packages.\n\n Sample return date:\n { 'updatename': '1.2.3-45', ... }\n '''\n cmd = ['softwareupdate', '--list']\n out = salt.utils.mac_utils.execute_return_result(cmd)\n\n # rexp parses lines that look like the following:\n # * Safari6.1.2MountainLion-6.1.2\n # Safari (6.1.2), 51679K [recommended]\n # - iCal-1.0.2\n # iCal, 1.0.2, 6520K\n rexp = re.compile('(?m)^ [*|-] '\n r'([^ ].*)[\\r\\n].*\\(([^\\)]+)')\n\n if salt.utils.data.is_true(recommended):\n # rexp parses lines that look like the following:\n # * Safari6.1.2MountainLion-6.1.2\n # Safari (6.1.2), 51679K [recommended]\n rexp = re.compile('(?m)^ [*] '\n r'([^ ].*)[\\r\\n].*\\(([^\\)]+)')\n\n keys = ['name', 'version']\n _get = lambda l, k: l[keys.index(k)]\n\n updates = rexp.findall(out)\n\n ret = {}\n for line in updates:\n name = _get(line, 'name')\n version_num = _get(line, 'version')\n ret[name] = version_num\n\n if not salt.utils.data.is_true(restart):\n return ret\n\n # rexp parses lines that look like the following:\n # * Safari6.1.2MountainLion-6.1.2\n # Safari (6.1.2), 51679K [recommended] [restart]\n rexp1 = re.compile('(?m)^ [*|-] '\n r'([^ ].*)[\\r\\n].*restart*')\n\n restart_updates = rexp1.findall(out)\n ret_restart = {}\n for update in ret:\n if update in restart_updates:\n ret_restart[update] = ret[update]\n\n return ret_restart\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored() def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out) def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on' def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name) def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads() def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads() def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default' def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
saltstack/salt
salt/modules/mac_softwareupdate.py
update
python
def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name)
Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L276-L297
[ "def execute_return_success(cmd):\n '''\n Executes the passed command. Returns True if successful\n\n :param str cmd: The command to run\n\n :return: True if successful, otherwise False\n :rtype: bool\n\n :raises: Error if command fails or is not supported\n '''\n\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return True\n", "def update_available(name):\n '''\n Check whether or not an update is available with a given name.\n\n :param str name: The name of the update to look for\n\n :return: True if available, False if not\n :rtype: bool\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' softwareupdate.update_available <update-name>\n salt '*' softwareupdate.update_available \"<update with whitespace>\"\n '''\n return name in _get_available()\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored() def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out) def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on' def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads() def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads() def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default' def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
saltstack/salt
salt/modules/mac_softwareupdate.py
list_downloads
python
def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret
Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L319-L349
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def os_walk(top, *args, **kwargs):\n '''\n This is a helper than ensures that all paths returned from os.walk are\n unicode.\n '''\n if six.PY2 and salt.utils.platform.is_windows():\n top_query = top\n else:\n top_query = salt.utils.stringutils.to_str(top)\n for item in os.walk(top_query, *args, **kwargs):\n yield salt.utils.data.decode(item, preserve_tuples=True)\n", "def _get_available(recommended=False, restart=False):\n '''\n Utility function to get all available update packages.\n\n Sample return date:\n { 'updatename': '1.2.3-45', ... }\n '''\n cmd = ['softwareupdate', '--list']\n out = salt.utils.mac_utils.execute_return_result(cmd)\n\n # rexp parses lines that look like the following:\n # * Safari6.1.2MountainLion-6.1.2\n # Safari (6.1.2), 51679K [recommended]\n # - iCal-1.0.2\n # iCal, 1.0.2, 6520K\n rexp = re.compile('(?m)^ [*|-] '\n r'([^ ].*)[\\r\\n].*\\(([^\\)]+)')\n\n if salt.utils.data.is_true(recommended):\n # rexp parses lines that look like the following:\n # * Safari6.1.2MountainLion-6.1.2\n # Safari (6.1.2), 51679K [recommended]\n rexp = re.compile('(?m)^ [*] '\n r'([^ ].*)[\\r\\n].*\\(([^\\)]+)')\n\n keys = ['name', 'version']\n _get = lambda l, k: l[keys.index(k)]\n\n updates = rexp.findall(out)\n\n ret = {}\n for line in updates:\n name = _get(line, 'name')\n version_num = _get(line, 'version')\n ret[name] = version_num\n\n if not salt.utils.data.is_true(restart):\n return ret\n\n # rexp parses lines that look like the following:\n # * Safari6.1.2MountainLion-6.1.2\n # Safari (6.1.2), 51679K [recommended] [restart]\n rexp1 = re.compile('(?m)^ [*|-] '\n r'([^ ].*)[\\r\\n].*restart*')\n\n restart_updates = rexp1.findall(out)\n ret_restart = {}\n for update in ret:\n if update in restart_updates:\n ret_restart[update] = ret[update]\n\n return ret_restart\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored() def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out) def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on' def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name) def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads() def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads() def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default' def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
saltstack/salt
salt/modules/mac_softwareupdate.py
download
python
def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads()
Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L352-L377
[ "def execute_return_success(cmd):\n '''\n Executes the passed command. Returns True if successful\n\n :param str cmd: The command to run\n\n :return: True if successful, otherwise False\n :rtype: bool\n\n :raises: Error if command fails or is not supported\n '''\n\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return True\n", "def update_available(name):\n '''\n Check whether or not an update is available with a given name.\n\n :param str name: The name of the update to look for\n\n :return: True if available, False if not\n :rtype: bool\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' softwareupdate.update_available <update-name>\n salt '*' softwareupdate.update_available \"<update with whitespace>\"\n '''\n return name in _get_available()\n", "def list_downloads():\n '''\n Return a list of all updates that have been downloaded locally.\n\n :return: A list of updates that have been downloaded\n :rtype: list\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' softwareupdate.list_downloads\n '''\n outfiles = []\n for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'):\n for f in files:\n outfiles.append(os.path.join(root, f))\n\n dist_files = []\n for f in outfiles:\n if f.endswith('.dist'):\n dist_files.append(f)\n\n ret = []\n for update in _get_available():\n for f in dist_files:\n with salt.utils.files.fopen(f) as fhr:\n if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()):\n ret.append(update)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored() def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out) def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on' def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name) def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads() def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default' def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
saltstack/salt
salt/modules/mac_softwareupdate.py
download_all
python
def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads()
Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L380-L406
[ "def download(name):\n '''\n Download a named update so that it can be installed later with the\n ``update`` or ``update_all`` functions\n\n :param str name: The update to download.\n\n :return: True if successful, otherwise False\n :rtype: bool\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' softwareupdate.download <update name>\n '''\n if not update_available(name):\n raise SaltInvocationError('Update not available: {0}'.format(name))\n\n if name in list_downloads():\n return True\n\n cmd = ['softwareupdate', '--download', name]\n salt.utils.mac_utils.execute_return_success(cmd)\n\n return name in list_downloads()\n", "def _get_available(recommended=False, restart=False):\n '''\n Utility function to get all available update packages.\n\n Sample return date:\n { 'updatename': '1.2.3-45', ... }\n '''\n cmd = ['softwareupdate', '--list']\n out = salt.utils.mac_utils.execute_return_result(cmd)\n\n # rexp parses lines that look like the following:\n # * Safari6.1.2MountainLion-6.1.2\n # Safari (6.1.2), 51679K [recommended]\n # - iCal-1.0.2\n # iCal, 1.0.2, 6520K\n rexp = re.compile('(?m)^ [*|-] '\n r'([^ ].*)[\\r\\n].*\\(([^\\)]+)')\n\n if salt.utils.data.is_true(recommended):\n # rexp parses lines that look like the following:\n # * Safari6.1.2MountainLion-6.1.2\n # Safari (6.1.2), 51679K [recommended]\n rexp = re.compile('(?m)^ [*] '\n r'([^ ].*)[\\r\\n].*\\(([^\\)]+)')\n\n keys = ['name', 'version']\n _get = lambda l, k: l[keys.index(k)]\n\n updates = rexp.findall(out)\n\n ret = {}\n for line in updates:\n name = _get(line, 'name')\n version_num = _get(line, 'version')\n ret[name] = version_num\n\n if not salt.utils.data.is_true(restart):\n return ret\n\n # rexp parses lines that look like the following:\n # * Safari6.1.2MountainLion-6.1.2\n # Safari (6.1.2), 51679K [recommended] [restart]\n rexp1 = re.compile('(?m)^ [*|-] '\n r'([^ ].*)[\\r\\n].*restart*')\n\n restart_updates = rexp1.findall(out)\n ret_restart = {}\n for update in ret:\n if update in restart_updates:\n ret_restart[update] = ret[update]\n\n return ret_restart\n", "def list_downloads():\n '''\n Return a list of all updates that have been downloaded locally.\n\n :return: A list of updates that have been downloaded\n :rtype: list\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' softwareupdate.list_downloads\n '''\n outfiles = []\n for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'):\n for f in files:\n outfiles.append(os.path.join(root, f))\n\n dist_files = []\n for f in outfiles:\n if f.endswith('.dist'):\n dist_files.append(f)\n\n ret = []\n for update in _get_available():\n for f in dist_files:\n with salt.utils.files.fopen(f) as fhr:\n if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()):\n ret.append(update)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored() def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out) def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on' def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name) def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads() def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default' def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
saltstack/salt
salt/modules/mac_softwareupdate.py
get_catalog
python
def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default'
.. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L409-L440
[ "def execute_return_result(cmd):\n '''\n Executes the passed command. Returns the standard out if successful\n\n :param str cmd: The command to run\n\n :return: The standard out of the command if successful, otherwise returns\n an error\n :rtype: str\n\n :raises: Error if command fails or is not supported\n '''\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return ret['stdout']\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored() def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out) def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on' def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name) def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads() def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads() def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
saltstack/salt
salt/modules/mac_softwareupdate.py
set_catalog
python
def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url
.. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L443-L470
[ "def execute_return_success(cmd):\n '''\n Executes the passed command. Returns True if successful\n\n :param str cmd: The command to run\n\n :return: True if successful, otherwise False\n :rtype: bool\n\n :raises: Error if command fails or is not supported\n '''\n\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return True\n", "def get_catalog():\n '''\n .. versionadded:: 2016.3.0\n\n Get the current catalog being used for update lookups. Will return a url if\n a custom catalog has been specified. Otherwise the word 'Default' will be\n returned\n\n :return: The catalog being used for update lookups\n :rtype: str\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' softwareupdates.get_catalog\n '''\n cmd = ['defaults',\n 'read',\n '/Library/Preferences/com.apple.SoftwareUpdate.plist']\n out = salt.utils.mac_utils.execute_return_result(cmd)\n\n if 'AppleCatalogURL' in out:\n cmd.append('AppleCatalogURL')\n out = salt.utils.mac_utils.execute_return_result(cmd)\n return out\n elif 'CatalogURL' in out:\n cmd.append('CatalogURL')\n out = salt.utils.mac_utils.execute_return_result(cmd)\n return out\n else:\n return 'Default'\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored() def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out) def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on' def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name) def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads() def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads() def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default' def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
saltstack/salt
salt/modules/mac_softwareupdate.py
reset_catalog
python
def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
.. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L473-L498
[ "def execute_return_success(cmd):\n '''\n Executes the passed command. Returns True if successful\n\n :param str cmd: The command to run\n\n :return: True if successful, otherwise False\n :rtype: bool\n\n :raises: Error if command fails or is not supported\n '''\n\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return True\n", "def get_catalog():\n '''\n .. versionadded:: 2016.3.0\n\n Get the current catalog being used for update lookups. Will return a url if\n a custom catalog has been specified. Otherwise the word 'Default' will be\n returned\n\n :return: The catalog being used for update lookups\n :rtype: str\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' softwareupdates.get_catalog\n '''\n cmd = ['defaults',\n 'read',\n '/Library/Preferences/com.apple.SoftwareUpdate.plist']\n out = salt.utils.mac_utils.execute_return_result(cmd)\n\n if 'AppleCatalogURL' in out:\n cmd.append('AppleCatalogURL')\n out = salt.utils.mac_utils.execute_return_result(cmd)\n return out\n elif 'CatalogURL' in out:\n cmd.append('CatalogURL')\n out = salt.utils.mac_utils.execute_return_result(cmd)\n return out\n else:\n return 'Default'\n" ]
# -*- coding: utf-8 -*- ''' Support for the softwareupdate command on MacOS. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import re import os # import salt libs import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = 'softwareupdate' def __virtual__(): ''' Only for MacOS ''' if not salt.utils.platform.is_darwin(): return (False, 'The softwareupdate module could not be loaded: ' 'module only works on MacOS systems.') return __virtualname__ def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] # - iCal-1.0.2 # iCal, 1.0.2, 6520K rexp = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*\(([^\)]+)') if salt.utils.data.is_true(recommended): # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] rexp = re.compile('(?m)^ [*] ' r'([^ ].*)[\r\n].*\(([^\)]+)') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] updates = rexp.findall(out) ret = {} for line in updates: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num if not salt.utils.data.is_true(restart): return ret # rexp parses lines that look like the following: # * Safari6.1.2MountainLion-6.1.2 # Safari (6.1.2), 51679K [recommended] [restart] rexp1 = re.compile('(?m)^ [*|-] ' r'([^ ].*)[\r\n].*restart*') restart_updates = rexp1.findall(out) ret_restart = {} for update in ret: if update in restart_updates: ret_restart[update] = ret[update] return ret_restart def list_available(recommended=False, restart=False): ''' List all available updates. :param bool recommended: Show only recommended updates. :param bool restart: Show only updates that require a restart. :return: Returns a dictionary containing the updates :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.list_available ''' return _get_available(recommended, restart) def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name: The name of the update to add to the ignore list. :ptype: str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.ignore <update-name> ''' # remove everything after and including the '-' in the updates name. to_ignore = name.rsplit('-', 1)[0] cmd = ['softwareupdate', '--ignore', to_ignore] salt.utils.mac_utils.execute_return_success(cmd) return to_ignore in list_ignored() def list_ignored(): ''' List all updates that have been ignored. Ignored updates are shown without the '-' and version number at the end, this is how the softwareupdate command works. :return: The list of ignored updates :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_ignored ''' cmd = ['softwareupdate', '--list', '--ignore'] out = salt.utils.mac_utils.execute_return_result(cmd) # rep parses lines that look like the following: # "Safari6.1.2MountainLion-6.1.2", # or: # Safari6.1.2MountainLion-6.1.2 rexp = re.compile('(?m)^ ["]?' r'([^,|\s].*[^"|\n|,])[,|"]?') return rexp.findall(out) def reset_ignored(): ''' Make sure the ignored updates are not ignored anymore, returns a list of the updates that are no longer ignored. :return: True if the list was reset, Otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.reset_ignored ''' cmd = ['softwareupdate', '--reset-ignored'] salt.utils.mac_utils.execute_return_success(cmd) return list_ignored() == [] def schedule_enabled(): ''' Check the status of automatic update scheduling. :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enabled ''' cmd = ['softwareupdate', '--schedule'] ret = salt.utils.mac_utils.execute_return_result(cmd) enabled = ret.split()[-1] return salt.utils.mac_utils.validate_enabled(enabled) == 'on' def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if scheduling is enabled, False if disabled :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.schedule_enable on|off ''' status = salt.utils.mac_utils.validate_enabled(enable) cmd = ['softwareupdate', '--schedule', salt.utils.mac_utils.validate_enabled(status)] salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A dictionary containing the updates that were installed and the status of its installation. If no updates were installed an empty dictionary is returned. :rtype: dict CLI Example: .. code-block:: bash salt '*' softwareupdate.update_all ''' to_update = _get_available(recommended, restart) if not to_update: return {} for _update in to_update: cmd = ['softwareupdate', '--install', _update] salt.utils.mac_utils.execute_return_success(cmd) ret = {} updates_left = _get_available() for _update in to_update: ret[_update] = True if _update not in updates_left else False return ret def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name) def update_available(name): ''' Check whether or not an update is available with a given name. :param str name: The name of the update to look for :return: True if available, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update_available <update-name> salt '*' softwareupdate.update_available "<update with whitespace>" ''' return name in _get_available() def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads() def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads() def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default' def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url
saltstack/salt
salt/modules/etcd_mod.py
get_
python
def get_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config salt myminion etcd.get /path/to/key recurse=True profile=my_etcd_config salt myminion etcd.get /path/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) if recurse: return client.tree(key) else: return client.get(key, recurse=recurse)
.. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config salt myminion etcd.get /path/to/key recurse=True profile=my_etcd_config salt myminion etcd.get /path/to/key host=127.0.0.1 port=2379
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L76-L95
null
# -*- coding: utf-8 -*- ''' Execution module to work with etcd :depends: - python-etcd Configuration ------------- To work with an etcd server you must configure an etcd profile. The etcd config can be set in either the Salt Minion configuration file or in pillar: .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 It is technically possible to configure etcd without using a profile, but this is not considered to be a best practice, especially when multiple etcd servers or clusters are available. .. code-block:: yaml etcd.host: 127.0.0.1 etcd.port: 4001 .. note:: The etcd configuration can also be set in the Salt Master config file, but in order to use any etcd configurations defined in the Salt Master config, the :conf_master:`pillar_opts` must be set to ``True``. Be aware that setting ``pillar_opts`` to ``True`` has security implications as this makes all master configuration settings available in all minion's pillars. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import third party libs try: import salt.utils.etcd_util # pylint: disable=W0611 HAS_LIBS = True except ImportError: HAS_LIBS = False __virtualname__ = 'etcd' # Set up logging log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'get_': 'get', 'set_': 'set', 'rm_': 'rm', 'ls_': 'ls' } def __virtual__(): ''' Only return if python-etcd is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The etcd_mod execution module cannot be loaded: ' 'python etcd library not available.') def set_(key, value, profile=None, ttl=None, directory=False, **kwargs): ''' .. versionadded:: 2014.7.0 Set a key in etcd by direct path. Optionally, create a directory or set a TTL on the key. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.set /path/to/key value salt myminion etcd.set /path/to/key value profile=my_etcd_config salt myminion etcd.set /path/to/key value host=127.0.0.1 port=2379 salt myminion etcd.set /path/to/dir '' directory=True salt myminion etcd.set /path/to/key value ttl=5 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.set(key, value, ttl=ttl, directory=directory) def update(fields, path='', profile=None, **kwargs): ''' .. versionadded:: 2016.3.0 Sets a dictionary of values in one call. Useful for large updates in syndic environments. The dictionary can contain a mix of formats such as: .. code-block:: python { '/some/example/key': 'bar', '/another/example/key': 'baz' } Or it may be a straight dictionary, which will be flattened to look like the above format: .. code-block:: python { 'some': { 'example': { 'key': 'bar' } }, 'another': { 'example': { 'key': 'baz' } } } You can even mix the two formats and it will be flattened to the first format. Leading and trailing '/' will be removed. Empty directories can be created by setting the value of the key to an empty dictionary. The 'path' parameter will optionally set the root of the path to use. CLI Example: .. code-block:: bash salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" profile=my_etcd_config salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" host=127.0.0.1 port=2379 salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" path='/some/root' ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.update(fields, path) def watch(key, recurse=False, profile=None, timeout=0, index=None, **kwargs): ''' .. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key changed or not, the path to the key that changed and whether it is a directory or not. If something catastrophic happens, returns {} CLI Example: .. code-block:: bash salt myminion etcd.watch /path/to/key salt myminion etcd.watch /path/to/key timeout=10 salt myminion etcd.watch /patch/to/key profile=my_etcd_config index=10 salt myminion etcd.watch /patch/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.watch(key, recurse=recurse, timeout=timeout, index=index) def ls_(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Return all keys and dirs inside a specific path. Returns an empty dict on failure. CLI Example: .. code-block:: bash salt myminion etcd.ls /path/to/dir/ salt myminion etcd.ls /path/to/dir/ profile=my_etcd_config salt myminion etcd.ls /path/to/dir/ host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.ls(path) def rm_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Delete a key from etcd. Returns True if the key was deleted, False if it was not and None if there was a failure. CLI Example: .. code-block:: bash salt myminion etcd.rm /path/to/key salt myminion etcd.rm /path/to/key profile=my_etcd_config salt myminion etcd.rm /path/to/key host=127.0.0.1 port=2379 salt myminion etcd.rm /path/to/dir recurse=True profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.rm(key, recurse=recurse) def tree(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Recurse through etcd and return all values. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.tree salt myminion etcd.tree profile=my_etcd_config salt myminion etcd.tree host=127.0.0.1 port=2379 salt myminion etcd.tree /path/to/keys profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.tree(path)
saltstack/salt
salt/modules/etcd_mod.py
set_
python
def set_(key, value, profile=None, ttl=None, directory=False, **kwargs): ''' .. versionadded:: 2014.7.0 Set a key in etcd by direct path. Optionally, create a directory or set a TTL on the key. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.set /path/to/key value salt myminion etcd.set /path/to/key value profile=my_etcd_config salt myminion etcd.set /path/to/key value host=127.0.0.1 port=2379 salt myminion etcd.set /path/to/dir '' directory=True salt myminion etcd.set /path/to/key value ttl=5 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.set(key, value, ttl=ttl, directory=directory)
.. versionadded:: 2014.7.0 Set a key in etcd by direct path. Optionally, create a directory or set a TTL on the key. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.set /path/to/key value salt myminion etcd.set /path/to/key value profile=my_etcd_config salt myminion etcd.set /path/to/key value host=127.0.0.1 port=2379 salt myminion etcd.set /path/to/dir '' directory=True salt myminion etcd.set /path/to/key value ttl=5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L98-L117
null
# -*- coding: utf-8 -*- ''' Execution module to work with etcd :depends: - python-etcd Configuration ------------- To work with an etcd server you must configure an etcd profile. The etcd config can be set in either the Salt Minion configuration file or in pillar: .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 It is technically possible to configure etcd without using a profile, but this is not considered to be a best practice, especially when multiple etcd servers or clusters are available. .. code-block:: yaml etcd.host: 127.0.0.1 etcd.port: 4001 .. note:: The etcd configuration can also be set in the Salt Master config file, but in order to use any etcd configurations defined in the Salt Master config, the :conf_master:`pillar_opts` must be set to ``True``. Be aware that setting ``pillar_opts`` to ``True`` has security implications as this makes all master configuration settings available in all minion's pillars. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import third party libs try: import salt.utils.etcd_util # pylint: disable=W0611 HAS_LIBS = True except ImportError: HAS_LIBS = False __virtualname__ = 'etcd' # Set up logging log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'get_': 'get', 'set_': 'set', 'rm_': 'rm', 'ls_': 'ls' } def __virtual__(): ''' Only return if python-etcd is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The etcd_mod execution module cannot be loaded: ' 'python etcd library not available.') def get_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config salt myminion etcd.get /path/to/key recurse=True profile=my_etcd_config salt myminion etcd.get /path/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) if recurse: return client.tree(key) else: return client.get(key, recurse=recurse) def update(fields, path='', profile=None, **kwargs): ''' .. versionadded:: 2016.3.0 Sets a dictionary of values in one call. Useful for large updates in syndic environments. The dictionary can contain a mix of formats such as: .. code-block:: python { '/some/example/key': 'bar', '/another/example/key': 'baz' } Or it may be a straight dictionary, which will be flattened to look like the above format: .. code-block:: python { 'some': { 'example': { 'key': 'bar' } }, 'another': { 'example': { 'key': 'baz' } } } You can even mix the two formats and it will be flattened to the first format. Leading and trailing '/' will be removed. Empty directories can be created by setting the value of the key to an empty dictionary. The 'path' parameter will optionally set the root of the path to use. CLI Example: .. code-block:: bash salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" profile=my_etcd_config salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" host=127.0.0.1 port=2379 salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" path='/some/root' ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.update(fields, path) def watch(key, recurse=False, profile=None, timeout=0, index=None, **kwargs): ''' .. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key changed or not, the path to the key that changed and whether it is a directory or not. If something catastrophic happens, returns {} CLI Example: .. code-block:: bash salt myminion etcd.watch /path/to/key salt myminion etcd.watch /path/to/key timeout=10 salt myminion etcd.watch /patch/to/key profile=my_etcd_config index=10 salt myminion etcd.watch /patch/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.watch(key, recurse=recurse, timeout=timeout, index=index) def ls_(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Return all keys and dirs inside a specific path. Returns an empty dict on failure. CLI Example: .. code-block:: bash salt myminion etcd.ls /path/to/dir/ salt myminion etcd.ls /path/to/dir/ profile=my_etcd_config salt myminion etcd.ls /path/to/dir/ host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.ls(path) def rm_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Delete a key from etcd. Returns True if the key was deleted, False if it was not and None if there was a failure. CLI Example: .. code-block:: bash salt myminion etcd.rm /path/to/key salt myminion etcd.rm /path/to/key profile=my_etcd_config salt myminion etcd.rm /path/to/key host=127.0.0.1 port=2379 salt myminion etcd.rm /path/to/dir recurse=True profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.rm(key, recurse=recurse) def tree(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Recurse through etcd and return all values. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.tree salt myminion etcd.tree profile=my_etcd_config salt myminion etcd.tree host=127.0.0.1 port=2379 salt myminion etcd.tree /path/to/keys profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.tree(path)
saltstack/salt
salt/modules/etcd_mod.py
update
python
def update(fields, path='', profile=None, **kwargs): ''' .. versionadded:: 2016.3.0 Sets a dictionary of values in one call. Useful for large updates in syndic environments. The dictionary can contain a mix of formats such as: .. code-block:: python { '/some/example/key': 'bar', '/another/example/key': 'baz' } Or it may be a straight dictionary, which will be flattened to look like the above format: .. code-block:: python { 'some': { 'example': { 'key': 'bar' } }, 'another': { 'example': { 'key': 'baz' } } } You can even mix the two formats and it will be flattened to the first format. Leading and trailing '/' will be removed. Empty directories can be created by setting the value of the key to an empty dictionary. The 'path' parameter will optionally set the root of the path to use. CLI Example: .. code-block:: bash salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" profile=my_etcd_config salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" host=127.0.0.1 port=2379 salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" path='/some/root' ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.update(fields, path)
.. versionadded:: 2016.3.0 Sets a dictionary of values in one call. Useful for large updates in syndic environments. The dictionary can contain a mix of formats such as: .. code-block:: python { '/some/example/key': 'bar', '/another/example/key': 'baz' } Or it may be a straight dictionary, which will be flattened to look like the above format: .. code-block:: python { 'some': { 'example': { 'key': 'bar' } }, 'another': { 'example': { 'key': 'baz' } } } You can even mix the two formats and it will be flattened to the first format. Leading and trailing '/' will be removed. Empty directories can be created by setting the value of the key to an empty dictionary. The 'path' parameter will optionally set the root of the path to use. CLI Example: .. code-block:: bash salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" profile=my_etcd_config salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" host=127.0.0.1 port=2379 salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" path='/some/root'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L120-L171
null
# -*- coding: utf-8 -*- ''' Execution module to work with etcd :depends: - python-etcd Configuration ------------- To work with an etcd server you must configure an etcd profile. The etcd config can be set in either the Salt Minion configuration file or in pillar: .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 It is technically possible to configure etcd without using a profile, but this is not considered to be a best practice, especially when multiple etcd servers or clusters are available. .. code-block:: yaml etcd.host: 127.0.0.1 etcd.port: 4001 .. note:: The etcd configuration can also be set in the Salt Master config file, but in order to use any etcd configurations defined in the Salt Master config, the :conf_master:`pillar_opts` must be set to ``True``. Be aware that setting ``pillar_opts`` to ``True`` has security implications as this makes all master configuration settings available in all minion's pillars. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import third party libs try: import salt.utils.etcd_util # pylint: disable=W0611 HAS_LIBS = True except ImportError: HAS_LIBS = False __virtualname__ = 'etcd' # Set up logging log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'get_': 'get', 'set_': 'set', 'rm_': 'rm', 'ls_': 'ls' } def __virtual__(): ''' Only return if python-etcd is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The etcd_mod execution module cannot be loaded: ' 'python etcd library not available.') def get_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config salt myminion etcd.get /path/to/key recurse=True profile=my_etcd_config salt myminion etcd.get /path/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) if recurse: return client.tree(key) else: return client.get(key, recurse=recurse) def set_(key, value, profile=None, ttl=None, directory=False, **kwargs): ''' .. versionadded:: 2014.7.0 Set a key in etcd by direct path. Optionally, create a directory or set a TTL on the key. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.set /path/to/key value salt myminion etcd.set /path/to/key value profile=my_etcd_config salt myminion etcd.set /path/to/key value host=127.0.0.1 port=2379 salt myminion etcd.set /path/to/dir '' directory=True salt myminion etcd.set /path/to/key value ttl=5 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.set(key, value, ttl=ttl, directory=directory) def watch(key, recurse=False, profile=None, timeout=0, index=None, **kwargs): ''' .. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key changed or not, the path to the key that changed and whether it is a directory or not. If something catastrophic happens, returns {} CLI Example: .. code-block:: bash salt myminion etcd.watch /path/to/key salt myminion etcd.watch /path/to/key timeout=10 salt myminion etcd.watch /patch/to/key profile=my_etcd_config index=10 salt myminion etcd.watch /patch/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.watch(key, recurse=recurse, timeout=timeout, index=index) def ls_(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Return all keys and dirs inside a specific path. Returns an empty dict on failure. CLI Example: .. code-block:: bash salt myminion etcd.ls /path/to/dir/ salt myminion etcd.ls /path/to/dir/ profile=my_etcd_config salt myminion etcd.ls /path/to/dir/ host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.ls(path) def rm_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Delete a key from etcd. Returns True if the key was deleted, False if it was not and None if there was a failure. CLI Example: .. code-block:: bash salt myminion etcd.rm /path/to/key salt myminion etcd.rm /path/to/key profile=my_etcd_config salt myminion etcd.rm /path/to/key host=127.0.0.1 port=2379 salt myminion etcd.rm /path/to/dir recurse=True profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.rm(key, recurse=recurse) def tree(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Recurse through etcd and return all values. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.tree salt myminion etcd.tree profile=my_etcd_config salt myminion etcd.tree host=127.0.0.1 port=2379 salt myminion etcd.tree /path/to/keys profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.tree(path)
saltstack/salt
salt/modules/etcd_mod.py
watch
python
def watch(key, recurse=False, profile=None, timeout=0, index=None, **kwargs): ''' .. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key changed or not, the path to the key that changed and whether it is a directory or not. If something catastrophic happens, returns {} CLI Example: .. code-block:: bash salt myminion etcd.watch /path/to/key salt myminion etcd.watch /path/to/key timeout=10 salt myminion etcd.watch /patch/to/key profile=my_etcd_config index=10 salt myminion etcd.watch /patch/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.watch(key, recurse=recurse, timeout=timeout, index=index)
.. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key changed or not, the path to the key that changed and whether it is a directory or not. If something catastrophic happens, returns {} CLI Example: .. code-block:: bash salt myminion etcd.watch /path/to/key salt myminion etcd.watch /path/to/key timeout=10 salt myminion etcd.watch /patch/to/key profile=my_etcd_config index=10 salt myminion etcd.watch /patch/to/key host=127.0.0.1 port=2379
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L174-L196
null
# -*- coding: utf-8 -*- ''' Execution module to work with etcd :depends: - python-etcd Configuration ------------- To work with an etcd server you must configure an etcd profile. The etcd config can be set in either the Salt Minion configuration file or in pillar: .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 It is technically possible to configure etcd without using a profile, but this is not considered to be a best practice, especially when multiple etcd servers or clusters are available. .. code-block:: yaml etcd.host: 127.0.0.1 etcd.port: 4001 .. note:: The etcd configuration can also be set in the Salt Master config file, but in order to use any etcd configurations defined in the Salt Master config, the :conf_master:`pillar_opts` must be set to ``True``. Be aware that setting ``pillar_opts`` to ``True`` has security implications as this makes all master configuration settings available in all minion's pillars. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import third party libs try: import salt.utils.etcd_util # pylint: disable=W0611 HAS_LIBS = True except ImportError: HAS_LIBS = False __virtualname__ = 'etcd' # Set up logging log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'get_': 'get', 'set_': 'set', 'rm_': 'rm', 'ls_': 'ls' } def __virtual__(): ''' Only return if python-etcd is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The etcd_mod execution module cannot be loaded: ' 'python etcd library not available.') def get_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config salt myminion etcd.get /path/to/key recurse=True profile=my_etcd_config salt myminion etcd.get /path/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) if recurse: return client.tree(key) else: return client.get(key, recurse=recurse) def set_(key, value, profile=None, ttl=None, directory=False, **kwargs): ''' .. versionadded:: 2014.7.0 Set a key in etcd by direct path. Optionally, create a directory or set a TTL on the key. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.set /path/to/key value salt myminion etcd.set /path/to/key value profile=my_etcd_config salt myminion etcd.set /path/to/key value host=127.0.0.1 port=2379 salt myminion etcd.set /path/to/dir '' directory=True salt myminion etcd.set /path/to/key value ttl=5 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.set(key, value, ttl=ttl, directory=directory) def update(fields, path='', profile=None, **kwargs): ''' .. versionadded:: 2016.3.0 Sets a dictionary of values in one call. Useful for large updates in syndic environments. The dictionary can contain a mix of formats such as: .. code-block:: python { '/some/example/key': 'bar', '/another/example/key': 'baz' } Or it may be a straight dictionary, which will be flattened to look like the above format: .. code-block:: python { 'some': { 'example': { 'key': 'bar' } }, 'another': { 'example': { 'key': 'baz' } } } You can even mix the two formats and it will be flattened to the first format. Leading and trailing '/' will be removed. Empty directories can be created by setting the value of the key to an empty dictionary. The 'path' parameter will optionally set the root of the path to use. CLI Example: .. code-block:: bash salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" profile=my_etcd_config salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" host=127.0.0.1 port=2379 salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" path='/some/root' ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.update(fields, path) def ls_(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Return all keys and dirs inside a specific path. Returns an empty dict on failure. CLI Example: .. code-block:: bash salt myminion etcd.ls /path/to/dir/ salt myminion etcd.ls /path/to/dir/ profile=my_etcd_config salt myminion etcd.ls /path/to/dir/ host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.ls(path) def rm_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Delete a key from etcd. Returns True if the key was deleted, False if it was not and None if there was a failure. CLI Example: .. code-block:: bash salt myminion etcd.rm /path/to/key salt myminion etcd.rm /path/to/key profile=my_etcd_config salt myminion etcd.rm /path/to/key host=127.0.0.1 port=2379 salt myminion etcd.rm /path/to/dir recurse=True profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.rm(key, recurse=recurse) def tree(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Recurse through etcd and return all values. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.tree salt myminion etcd.tree profile=my_etcd_config salt myminion etcd.tree host=127.0.0.1 port=2379 salt myminion etcd.tree /path/to/keys profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.tree(path)
saltstack/salt
salt/modules/etcd_mod.py
ls_
python
def ls_(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Return all keys and dirs inside a specific path. Returns an empty dict on failure. CLI Example: .. code-block:: bash salt myminion etcd.ls /path/to/dir/ salt myminion etcd.ls /path/to/dir/ profile=my_etcd_config salt myminion etcd.ls /path/to/dir/ host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.ls(path)
.. versionadded:: 2014.7.0 Return all keys and dirs inside a specific path. Returns an empty dict on failure. CLI Example: .. code-block:: bash salt myminion etcd.ls /path/to/dir/ salt myminion etcd.ls /path/to/dir/ profile=my_etcd_config salt myminion etcd.ls /path/to/dir/ host=127.0.0.1 port=2379
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L199-L216
null
# -*- coding: utf-8 -*- ''' Execution module to work with etcd :depends: - python-etcd Configuration ------------- To work with an etcd server you must configure an etcd profile. The etcd config can be set in either the Salt Minion configuration file or in pillar: .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 It is technically possible to configure etcd without using a profile, but this is not considered to be a best practice, especially when multiple etcd servers or clusters are available. .. code-block:: yaml etcd.host: 127.0.0.1 etcd.port: 4001 .. note:: The etcd configuration can also be set in the Salt Master config file, but in order to use any etcd configurations defined in the Salt Master config, the :conf_master:`pillar_opts` must be set to ``True``. Be aware that setting ``pillar_opts`` to ``True`` has security implications as this makes all master configuration settings available in all minion's pillars. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import third party libs try: import salt.utils.etcd_util # pylint: disable=W0611 HAS_LIBS = True except ImportError: HAS_LIBS = False __virtualname__ = 'etcd' # Set up logging log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'get_': 'get', 'set_': 'set', 'rm_': 'rm', 'ls_': 'ls' } def __virtual__(): ''' Only return if python-etcd is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The etcd_mod execution module cannot be loaded: ' 'python etcd library not available.') def get_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config salt myminion etcd.get /path/to/key recurse=True profile=my_etcd_config salt myminion etcd.get /path/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) if recurse: return client.tree(key) else: return client.get(key, recurse=recurse) def set_(key, value, profile=None, ttl=None, directory=False, **kwargs): ''' .. versionadded:: 2014.7.0 Set a key in etcd by direct path. Optionally, create a directory or set a TTL on the key. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.set /path/to/key value salt myminion etcd.set /path/to/key value profile=my_etcd_config salt myminion etcd.set /path/to/key value host=127.0.0.1 port=2379 salt myminion etcd.set /path/to/dir '' directory=True salt myminion etcd.set /path/to/key value ttl=5 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.set(key, value, ttl=ttl, directory=directory) def update(fields, path='', profile=None, **kwargs): ''' .. versionadded:: 2016.3.0 Sets a dictionary of values in one call. Useful for large updates in syndic environments. The dictionary can contain a mix of formats such as: .. code-block:: python { '/some/example/key': 'bar', '/another/example/key': 'baz' } Or it may be a straight dictionary, which will be flattened to look like the above format: .. code-block:: python { 'some': { 'example': { 'key': 'bar' } }, 'another': { 'example': { 'key': 'baz' } } } You can even mix the two formats and it will be flattened to the first format. Leading and trailing '/' will be removed. Empty directories can be created by setting the value of the key to an empty dictionary. The 'path' parameter will optionally set the root of the path to use. CLI Example: .. code-block:: bash salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" profile=my_etcd_config salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" host=127.0.0.1 port=2379 salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" path='/some/root' ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.update(fields, path) def watch(key, recurse=False, profile=None, timeout=0, index=None, **kwargs): ''' .. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key changed or not, the path to the key that changed and whether it is a directory or not. If something catastrophic happens, returns {} CLI Example: .. code-block:: bash salt myminion etcd.watch /path/to/key salt myminion etcd.watch /path/to/key timeout=10 salt myminion etcd.watch /patch/to/key profile=my_etcd_config index=10 salt myminion etcd.watch /patch/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.watch(key, recurse=recurse, timeout=timeout, index=index) def rm_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Delete a key from etcd. Returns True if the key was deleted, False if it was not and None if there was a failure. CLI Example: .. code-block:: bash salt myminion etcd.rm /path/to/key salt myminion etcd.rm /path/to/key profile=my_etcd_config salt myminion etcd.rm /path/to/key host=127.0.0.1 port=2379 salt myminion etcd.rm /path/to/dir recurse=True profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.rm(key, recurse=recurse) def tree(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Recurse through etcd and return all values. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.tree salt myminion etcd.tree profile=my_etcd_config salt myminion etcd.tree host=127.0.0.1 port=2379 salt myminion etcd.tree /path/to/keys profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.tree(path)
saltstack/salt
salt/modules/etcd_mod.py
rm_
python
def rm_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Delete a key from etcd. Returns True if the key was deleted, False if it was not and None if there was a failure. CLI Example: .. code-block:: bash salt myminion etcd.rm /path/to/key salt myminion etcd.rm /path/to/key profile=my_etcd_config salt myminion etcd.rm /path/to/key host=127.0.0.1 port=2379 salt myminion etcd.rm /path/to/dir recurse=True profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.rm(key, recurse=recurse)
.. versionadded:: 2014.7.0 Delete a key from etcd. Returns True if the key was deleted, False if it was not and None if there was a failure. CLI Example: .. code-block:: bash salt myminion etcd.rm /path/to/key salt myminion etcd.rm /path/to/key profile=my_etcd_config salt myminion etcd.rm /path/to/key host=127.0.0.1 port=2379 salt myminion etcd.rm /path/to/dir recurse=True profile=my_etcd_config
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L219-L237
null
# -*- coding: utf-8 -*- ''' Execution module to work with etcd :depends: - python-etcd Configuration ------------- To work with an etcd server you must configure an etcd profile. The etcd config can be set in either the Salt Minion configuration file or in pillar: .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 It is technically possible to configure etcd without using a profile, but this is not considered to be a best practice, especially when multiple etcd servers or clusters are available. .. code-block:: yaml etcd.host: 127.0.0.1 etcd.port: 4001 .. note:: The etcd configuration can also be set in the Salt Master config file, but in order to use any etcd configurations defined in the Salt Master config, the :conf_master:`pillar_opts` must be set to ``True``. Be aware that setting ``pillar_opts`` to ``True`` has security implications as this makes all master configuration settings available in all minion's pillars. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import third party libs try: import salt.utils.etcd_util # pylint: disable=W0611 HAS_LIBS = True except ImportError: HAS_LIBS = False __virtualname__ = 'etcd' # Set up logging log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'get_': 'get', 'set_': 'set', 'rm_': 'rm', 'ls_': 'ls' } def __virtual__(): ''' Only return if python-etcd is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The etcd_mod execution module cannot be loaded: ' 'python etcd library not available.') def get_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config salt myminion etcd.get /path/to/key recurse=True profile=my_etcd_config salt myminion etcd.get /path/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) if recurse: return client.tree(key) else: return client.get(key, recurse=recurse) def set_(key, value, profile=None, ttl=None, directory=False, **kwargs): ''' .. versionadded:: 2014.7.0 Set a key in etcd by direct path. Optionally, create a directory or set a TTL on the key. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.set /path/to/key value salt myminion etcd.set /path/to/key value profile=my_etcd_config salt myminion etcd.set /path/to/key value host=127.0.0.1 port=2379 salt myminion etcd.set /path/to/dir '' directory=True salt myminion etcd.set /path/to/key value ttl=5 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.set(key, value, ttl=ttl, directory=directory) def update(fields, path='', profile=None, **kwargs): ''' .. versionadded:: 2016.3.0 Sets a dictionary of values in one call. Useful for large updates in syndic environments. The dictionary can contain a mix of formats such as: .. code-block:: python { '/some/example/key': 'bar', '/another/example/key': 'baz' } Or it may be a straight dictionary, which will be flattened to look like the above format: .. code-block:: python { 'some': { 'example': { 'key': 'bar' } }, 'another': { 'example': { 'key': 'baz' } } } You can even mix the two formats and it will be flattened to the first format. Leading and trailing '/' will be removed. Empty directories can be created by setting the value of the key to an empty dictionary. The 'path' parameter will optionally set the root of the path to use. CLI Example: .. code-block:: bash salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" profile=my_etcd_config salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" host=127.0.0.1 port=2379 salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" path='/some/root' ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.update(fields, path) def watch(key, recurse=False, profile=None, timeout=0, index=None, **kwargs): ''' .. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key changed or not, the path to the key that changed and whether it is a directory or not. If something catastrophic happens, returns {} CLI Example: .. code-block:: bash salt myminion etcd.watch /path/to/key salt myminion etcd.watch /path/to/key timeout=10 salt myminion etcd.watch /patch/to/key profile=my_etcd_config index=10 salt myminion etcd.watch /patch/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.watch(key, recurse=recurse, timeout=timeout, index=index) def ls_(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Return all keys and dirs inside a specific path. Returns an empty dict on failure. CLI Example: .. code-block:: bash salt myminion etcd.ls /path/to/dir/ salt myminion etcd.ls /path/to/dir/ profile=my_etcd_config salt myminion etcd.ls /path/to/dir/ host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.ls(path) def tree(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Recurse through etcd and return all values. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.tree salt myminion etcd.tree profile=my_etcd_config salt myminion etcd.tree host=127.0.0.1 port=2379 salt myminion etcd.tree /path/to/keys profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.tree(path)
saltstack/salt
salt/modules/etcd_mod.py
tree
python
def tree(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Recurse through etcd and return all values. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.tree salt myminion etcd.tree profile=my_etcd_config salt myminion etcd.tree host=127.0.0.1 port=2379 salt myminion etcd.tree /path/to/keys profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.tree(path)
.. versionadded:: 2014.7.0 Recurse through etcd and return all values. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.tree salt myminion etcd.tree profile=my_etcd_config salt myminion etcd.tree host=127.0.0.1 port=2379 salt myminion etcd.tree /path/to/keys profile=my_etcd_config
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L240-L257
null
# -*- coding: utf-8 -*- ''' Execution module to work with etcd :depends: - python-etcd Configuration ------------- To work with an etcd server you must configure an etcd profile. The etcd config can be set in either the Salt Minion configuration file or in pillar: .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 It is technically possible to configure etcd without using a profile, but this is not considered to be a best practice, especially when multiple etcd servers or clusters are available. .. code-block:: yaml etcd.host: 127.0.0.1 etcd.port: 4001 .. note:: The etcd configuration can also be set in the Salt Master config file, but in order to use any etcd configurations defined in the Salt Master config, the :conf_master:`pillar_opts` must be set to ``True``. Be aware that setting ``pillar_opts`` to ``True`` has security implications as this makes all master configuration settings available in all minion's pillars. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import third party libs try: import salt.utils.etcd_util # pylint: disable=W0611 HAS_LIBS = True except ImportError: HAS_LIBS = False __virtualname__ = 'etcd' # Set up logging log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'get_': 'get', 'set_': 'set', 'rm_': 'rm', 'ls_': 'ls' } def __virtual__(): ''' Only return if python-etcd is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The etcd_mod execution module cannot be loaded: ' 'python etcd library not available.') def get_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config salt myminion etcd.get /path/to/key recurse=True profile=my_etcd_config salt myminion etcd.get /path/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) if recurse: return client.tree(key) else: return client.get(key, recurse=recurse) def set_(key, value, profile=None, ttl=None, directory=False, **kwargs): ''' .. versionadded:: 2014.7.0 Set a key in etcd by direct path. Optionally, create a directory or set a TTL on the key. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.set /path/to/key value salt myminion etcd.set /path/to/key value profile=my_etcd_config salt myminion etcd.set /path/to/key value host=127.0.0.1 port=2379 salt myminion etcd.set /path/to/dir '' directory=True salt myminion etcd.set /path/to/key value ttl=5 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.set(key, value, ttl=ttl, directory=directory) def update(fields, path='', profile=None, **kwargs): ''' .. versionadded:: 2016.3.0 Sets a dictionary of values in one call. Useful for large updates in syndic environments. The dictionary can contain a mix of formats such as: .. code-block:: python { '/some/example/key': 'bar', '/another/example/key': 'baz' } Or it may be a straight dictionary, which will be flattened to look like the above format: .. code-block:: python { 'some': { 'example': { 'key': 'bar' } }, 'another': { 'example': { 'key': 'baz' } } } You can even mix the two formats and it will be flattened to the first format. Leading and trailing '/' will be removed. Empty directories can be created by setting the value of the key to an empty dictionary. The 'path' parameter will optionally set the root of the path to use. CLI Example: .. code-block:: bash salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" profile=my_etcd_config salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" host=127.0.0.1 port=2379 salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" path='/some/root' ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.update(fields, path) def watch(key, recurse=False, profile=None, timeout=0, index=None, **kwargs): ''' .. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key changed or not, the path to the key that changed and whether it is a directory or not. If something catastrophic happens, returns {} CLI Example: .. code-block:: bash salt myminion etcd.watch /path/to/key salt myminion etcd.watch /path/to/key timeout=10 salt myminion etcd.watch /patch/to/key profile=my_etcd_config index=10 salt myminion etcd.watch /patch/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.watch(key, recurse=recurse, timeout=timeout, index=index) def ls_(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Return all keys and dirs inside a specific path. Returns an empty dict on failure. CLI Example: .. code-block:: bash salt myminion etcd.ls /path/to/dir/ salt myminion etcd.ls /path/to/dir/ profile=my_etcd_config salt myminion etcd.ls /path/to/dir/ host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.ls(path) def rm_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Delete a key from etcd. Returns True if the key was deleted, False if it was not and None if there was a failure. CLI Example: .. code-block:: bash salt myminion etcd.rm /path/to/key salt myminion etcd.rm /path/to/key profile=my_etcd_config salt myminion etcd.rm /path/to/key host=127.0.0.1 port=2379 salt myminion etcd.rm /path/to/dir recurse=True profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.rm(key, recurse=recurse)
saltstack/salt
salt/utils/aws.py
creds
python
def creds(provider): ''' Return the credentials for AWS signing. This could be just the id and key specified in the provider configuration, or if the id or key is set to the literal string 'use-instance-role-credentials' creds will pull the instance role credentials from the meta data, cache them, and provide them instead. ''' # Declare globals global __AccessKeyId__, __SecretAccessKey__, __Token__, __Expiration__ ret_credentials = () # if id or key is 'use-instance-role-credentials', pull them from meta-data ## if needed if provider['id'] == IROLE_CODE or provider['key'] == IROLE_CODE: # Check to see if we have cache credentials that are still good if __Expiration__ != '': timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp < __Expiration__: # Current timestamp less than expiration fo cached credentials return __AccessKeyId__, __SecretAccessKey__, __Token__ # We don't have any cached credentials, or they are expired, get them # Connections to instance meta-data must fail fast and never be proxied try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() role = result.text except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/{0}".format(role), proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' data = result.json() __AccessKeyId__ = data['AccessKeyId'] __SecretAccessKey__ = data['SecretAccessKey'] __Token__ = data['Token'] __Expiration__ = data['Expiration'] ret_credentials = __AccessKeyId__, __SecretAccessKey__, __Token__ else: ret_credentials = provider['id'], provider['key'], '' if provider.get('role_arn') is not None: provider_shadow = provider.copy() provider_shadow.pop("role_arn", None) log.info("Assuming the role: %s", provider.get('role_arn')) ret_credentials = assumed_creds(provider_shadow, role_arn=provider.get('role_arn'), location='us-east-1') return ret_credentials
Return the credentials for AWS signing. This could be just the id and key specified in the provider configuration, or if the id or key is set to the literal string 'use-instance-role-credentials' creds will pull the instance role credentials from the meta data, cache them, and provide them instead.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L81-L141
[ "def assumed_creds(prov_dict, role_arn, location=None):\n valid_session_name_re = re.compile(\"[^a-z0-9A-Z+=,.@-]\")\n\n # current time in epoch seconds\n now = time.mktime(datetime.utcnow().timetuple())\n\n for key, creds in __AssumeCache__.items():\n if (creds[\"Expiration\"] - now) <= 120:\n __AssumeCache__.delete(key)\n\n if role_arn in __AssumeCache__:\n c = __AssumeCache__[role_arn]\n return c[\"AccessKeyId\"], c[\"SecretAccessKey\"], c[\"SessionToken\"]\n\n version = \"2011-06-15\"\n session_name = valid_session_name_re.sub('', salt.config.get_id({\"root_dir\": None})[0])[0:63]\n\n headers, requesturl = sig4(\n 'GET',\n 'sts.amazonaws.com',\n params={\n \"Version\": version,\n \"Action\": \"AssumeRole\",\n \"RoleSessionName\": session_name,\n \"RoleArn\": role_arn,\n \"Policy\": '{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\", \"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}',\n \"DurationSeconds\": \"3600\"\n },\n aws_api_version=version,\n data='',\n uri='/',\n prov_dict=prov_dict,\n product='sts',\n location=location,\n requesturl=\"https://sts.amazonaws.com/\"\n )\n headers[\"Accept\"] = \"application/json\"\n result = requests.request('GET', requesturl, headers=headers,\n data='',\n verify=True)\n\n if result.status_code >= 400:\n log.info('AssumeRole response: %s', result.content)\n result.raise_for_status()\n resp = result.json()\n\n data = resp[\"AssumeRoleResponse\"][\"AssumeRoleResult\"][\"Credentials\"]\n __AssumeCache__[role_arn] = data\n return data[\"AccessKeyId\"], data[\"SecretAccessKey\"], data[\"SessionToken\"]\n" ]
# -*- coding: utf-8 -*- ''' Connection library for AWS .. versionadded:: 2015.5.0 This is a base library used by a number of AWS services. :depends: requests ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import sys import time import binascii from datetime import datetime import hashlib import hmac import logging import salt.config import re import random from salt.ext import six # Import Salt libs import salt.utils.hashutils import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET # Import 3rd-party libs try: import requests HAS_REQUESTS = True # pylint: disable=W0612 except ImportError: HAS_REQUESTS = False # pylint: disable=W0612 # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, zip from salt.ext.six.moves.urllib.parse import urlencode, urlparse # pylint: enable=import-error,redefined-builtin,no-name-in-module log = logging.getLogger(__name__) DEFAULT_LOCATION = 'us-east-1' DEFAULT_AWS_API_VERSION = '2014-10-01' AWS_RETRY_CODES = [ 'RequestLimitExceeded', 'InsufficientInstanceCapacity', 'InternalError', 'Unavailable', 'InsufficientAddressCapacity', 'InsufficientReservedInstanceCapacity', ] AWS_METADATA_TIMEOUT = 3.05 AWS_MAX_RETRIES = 7 IROLE_CODE = 'use-instance-role-credentials' __AccessKeyId__ = '' __SecretAccessKey__ = '' __Token__ = '' __Expiration__ = '' __Location__ = '' __AssumeCache__ = {} def sleep_exponential_backoff(attempts): """ backoff an exponential amount of time to throttle requests during "API Rate Exceeded" failures as suggested by the AWS documentation here: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html and also here: https://docs.aws.amazon.com/general/latest/gr/api-retries.html Failure to implement this approach results in a failure rate of >30% when using salt-cloud with "--parallel" when creating 50 or more instances with a fixed delay of 2 seconds. A failure rate of >10% is observed when using the salt-api with an asynchronous client specified (runner_async). """ time.sleep(random.uniform(1, 2**attempts)) def sig2(method, endpoint, params, provider, aws_api_version): ''' Sign a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html ''' timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') # Retrieve access credentials from meta-data, or use provided access_key_id, secret_access_key, token = creds(provider) params_with_headers = params.copy() params_with_headers['AWSAccessKeyId'] = access_key_id params_with_headers['SignatureVersion'] = '2' params_with_headers['SignatureMethod'] = 'HmacSHA256' params_with_headers['Timestamp'] = '{0}'.format(timestamp) params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(list(map(params_with_headers.get, keys))) querystring = urlencode(list(zip(keys, values))) canonical = '{0}\n{1}\n/\n{2}'.format( method.encode('utf-8'), endpoint.encode('utf-8'), querystring.encode('utf-8'), ) hashed = hmac.new(secret_access_key, canonical, hashlib.sha256) sig = binascii.b2a_base64(hashed.digest()) params_with_headers['Signature'] = sig.strip() # Add in security token if we have one if token != '': params_with_headers['SecurityToken'] = token return params_with_headers def assumed_creds(prov_dict, role_arn, location=None): valid_session_name_re = re.compile("[^a-z0-9A-Z+=,.@-]") # current time in epoch seconds now = time.mktime(datetime.utcnow().timetuple()) for key, creds in __AssumeCache__.items(): if (creds["Expiration"] - now) <= 120: __AssumeCache__.delete(key) if role_arn in __AssumeCache__: c = __AssumeCache__[role_arn] return c["AccessKeyId"], c["SecretAccessKey"], c["SessionToken"] version = "2011-06-15" session_name = valid_session_name_re.sub('', salt.config.get_id({"root_dir": None})[0])[0:63] headers, requesturl = sig4( 'GET', 'sts.amazonaws.com', params={ "Version": version, "Action": "AssumeRole", "RoleSessionName": session_name, "RoleArn": role_arn, "Policy": '{"Version":"2012-10-17","Statement":[{"Sid":"Stmt1", "Effect":"Allow","Action":"*","Resource":"*"}]}', "DurationSeconds": "3600" }, aws_api_version=version, data='', uri='/', prov_dict=prov_dict, product='sts', location=location, requesturl="https://sts.amazonaws.com/" ) headers["Accept"] = "application/json" result = requests.request('GET', requesturl, headers=headers, data='', verify=True) if result.status_code >= 400: log.info('AssumeRole response: %s', result.content) result.raise_for_status() resp = result.json() data = resp["AssumeRoleResponse"]["AssumeRoleResult"]["Credentials"] __AssumeCache__[role_arn] = data return data["AccessKeyId"], data["SecretAccessKey"], data["SessionToken"] def sig4(method, endpoint, params, prov_dict, aws_api_version=DEFAULT_AWS_API_VERSION, location=None, product='ec2', uri='/', requesturl=None, data='', headers=None, role_arn=None, payload_hash=None): ''' Sign a query against AWS services using Signature Version 4 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html ''' timenow = datetime.utcnow() # Retrieve access credentials from meta-data, or use provided if role_arn is None: access_key_id, secret_access_key, token = creds(prov_dict) else: access_key_id, secret_access_key, token = assumed_creds(prov_dict, role_arn, location=location) if location is None: location = get_region_from_metadata() if location is None: location = DEFAULT_LOCATION params_with_headers = params.copy() if product not in ('s3', 'ssm'): params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(map(params_with_headers.get, keys)) querystring = urlencode(list(zip(keys, values))).replace('+', '%20') amzdate = timenow.strftime('%Y%m%dT%H%M%SZ') datestamp = timenow.strftime('%Y%m%d') new_headers = {} if isinstance(headers, dict): new_headers = headers.copy() # Create payload hash (hash of the request body content). For GET # requests, the payload is an empty string (''). if not payload_hash: payload_hash = salt.utils.hashutils.sha256_digest(data) new_headers['X-Amz-date'] = amzdate new_headers['host'] = endpoint new_headers['x-amz-content-sha256'] = payload_hash a_canonical_headers = [] a_signed_headers = [] if token != '': new_headers['X-Amz-security-token'] = token for header in sorted(new_headers.keys(), key=six.text_type.lower): lower_header = header.lower() a_canonical_headers.append('{0}:{1}'.format(lower_header, new_headers[header].strip())) a_signed_headers.append(lower_header) canonical_headers = '\n'.join(a_canonical_headers) + '\n' signed_headers = ';'.join(a_signed_headers) algorithm = 'AWS4-HMAC-SHA256' # Combine elements to create create canonical request canonical_request = '\n'.join(( method, uri, querystring, canonical_headers, signed_headers, payload_hash )) # Create the string to sign credential_scope = '/'.join((datestamp, location, product, 'aws4_request')) string_to_sign = '\n'.join(( algorithm, amzdate, credential_scope, salt.utils.hashutils.sha256_digest(canonical_request) )) # Create the signing key using the function defined above. signing_key = _sig_key( secret_access_key, datestamp, location, product ) # Sign the string_to_sign using the signing_key signature = hmac.new( signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest() # Add signing information to the request authorization_header = ( '{0} Credential={1}/{2}, SignedHeaders={3}, Signature={4}' ).format( algorithm, access_key_id, credential_scope, signed_headers, signature, ) new_headers['Authorization'] = authorization_header requesturl = '{0}?{1}'.format(requesturl, querystring) return new_headers, requesturl def _sign(key, msg): ''' Key derivation functions. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() def _sig_key(key, date_stamp, regionName, serviceName): ''' Get a signature key. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp) if regionName: kRegion = _sign(kDate, regionName) kService = _sign(kRegion, serviceName) else: kService = _sign(kDate, serviceName) kSigning = _sign(kService, 'aws4_request') return kSigning def query(params=None, setname=None, requesturl=None, location=None, return_url=False, return_root=False, opts=None, provider=None, endpoint=None, product='ec2', sigver='2'): ''' Perform a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html Regions and endpoints are documented at: http://docs.aws.amazon.com/general/latest/gr/rande.html Default ``product`` is ``ec2``. Valid ``product`` names are: .. code-block: yaml - autoscaling (Auto Scaling) - cloudformation (CloudFormation) - ec2 (Elastic Compute Cloud) - elasticache (ElastiCache) - elasticbeanstalk (Elastic BeanStalk) - elasticloadbalancing (Elastic Load Balancing) - elasticmapreduce (Elastic MapReduce) - iam (Identity and Access Management) - importexport (Import/Export) - monitoring (CloudWatch) - rds (Relational Database Service) - simpledb (SimpleDB) - sns (Simple Notification Service) - sqs (Simple Queue Service) ''' if params is None: params = {} if opts is None: opts = {} function = opts.get('function', (None, product)) providers = opts.get('providers', {}) if provider is None: prov_dict = providers.get(function[1], {}).get(product, {}) if prov_dict: driver = list(list(prov_dict.keys()))[0] provider = providers.get(driver, product) else: prov_dict = providers.get(provider, {}).get(product, {}) service_url = prov_dict.get('service_url', 'amazonaws.com') if not location: location = get_location(opts, prov_dict) if endpoint is None: if not requesturl: endpoint = prov_dict.get( 'endpoint', '{0}.{1}.{2}'.format(product, location, service_url) ) requesturl = 'https://{0}/'.format(endpoint) else: endpoint = urlparse(requesturl).netloc if endpoint == '': endpoint_err = ('Could not find a valid endpoint in the ' 'requesturl: {0}. Looking for something ' 'like https://some.aws.endpoint/?args').format( requesturl ) log.error(endpoint_err) if return_url is True: return {'error': endpoint_err}, requesturl return {'error': endpoint_err} log.debug('Using AWS endpoint: %s', endpoint) method = 'GET' aws_api_version = prov_dict.get( 'aws_api_version', prov_dict.get( '{0}_api_version'.format(product), DEFAULT_AWS_API_VERSION ) ) # Fallback to ec2's id & key if none is found, for this component if not prov_dict.get('id', None): prov_dict['id'] = providers.get(provider, {}).get('ec2', {}).get('id', {}) prov_dict['key'] = providers.get(provider, {}).get('ec2', {}).get('key', {}) if sigver == '4': headers, requesturl = sig4( method, endpoint, params, prov_dict, aws_api_version, location, product, requesturl=requesturl ) params_with_headers = {} else: params_with_headers = sig2( method, endpoint, params, prov_dict, aws_api_version ) headers = {} attempts = 0 while attempts < AWS_MAX_RETRIES: log.debug('AWS Request: %s', requesturl) log.trace('AWS Request Parameters: %s', params_with_headers) try: result = requests.get(requesturl, headers=headers, params=params_with_headers) log.debug('AWS Response Status Code: %s', result.status_code) log.trace( 'AWS Response Text: %s', result.text ) result.raise_for_status() break except requests.exceptions.HTTPError as exc: root = ET.fromstring(exc.response.content) data = xml.to_dict(root) # check to see if we should retry the query err_code = data.get('Errors', {}).get('Error', {}).get('Code', '') if attempts < AWS_MAX_RETRIES and err_code and err_code in AWS_RETRY_CODES: attempts += 1 log.error( 'AWS Response Status Code and Error: [%s %s] %s; ' 'Attempts remaining: %s', exc.response.status_code, exc, data, attempts ) sleep_exponential_backoff(attempts) continue log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} else: log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} root = ET.fromstring(result.text) items = root[1] if return_root is True: items = root if setname: if sys.version_info < (2, 7): children_len = len(root.getchildren()) else: children_len = len(root) for item in range(0, children_len): comps = root[item].tag.split('}') if comps[1] == setname: items = root[item] ret = [] for item in items: ret.append(xml.to_dict(item)) if return_url is True: return ret, requesturl return ret def get_region_from_metadata(): ''' Try to get region from instance identity document and cache it .. versionadded:: 2015.5.6 ''' global __Location__ if __Location__ == 'do-not-get-from-metadata': log.debug('Previously failed to get AWS region from metadata. Not trying again.') return None # Cached region if __Location__ != '': return __Location__ try: # Connections to instance meta-data must fail fast and never be proxied result = requests.get( "http://169.254.169.254/latest/dynamic/instance-identity/document", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) except requests.exceptions.RequestException: log.warning('Failed to get AWS region from instance metadata.', exc_info=True) # Do not try again __Location__ = 'do-not-get-from-metadata' return None try: region = result.json()['region'] __Location__ = region return __Location__ except (ValueError, KeyError): log.warning('Failed to decode JSON from instance metadata.') return None return None def get_location(opts=None, provider=None): ''' Return the region to use, in this order: opts['location'] provider['location'] get_region_from_metadata() DEFAULT_LOCATION ''' if opts is None: opts = {} ret = opts.get('location') if ret is None and provider is not None: ret = provider.get('location') if ret is None: ret = get_region_from_metadata() if ret is None: ret = DEFAULT_LOCATION return ret
saltstack/salt
salt/utils/aws.py
sig2
python
def sig2(method, endpoint, params, provider, aws_api_version): ''' Sign a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html ''' timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') # Retrieve access credentials from meta-data, or use provided access_key_id, secret_access_key, token = creds(provider) params_with_headers = params.copy() params_with_headers['AWSAccessKeyId'] = access_key_id params_with_headers['SignatureVersion'] = '2' params_with_headers['SignatureMethod'] = 'HmacSHA256' params_with_headers['Timestamp'] = '{0}'.format(timestamp) params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(list(map(params_with_headers.get, keys))) querystring = urlencode(list(zip(keys, values))) canonical = '{0}\n{1}\n/\n{2}'.format( method.encode('utf-8'), endpoint.encode('utf-8'), querystring.encode('utf-8'), ) hashed = hmac.new(secret_access_key, canonical, hashlib.sha256) sig = binascii.b2a_base64(hashed.digest()) params_with_headers['Signature'] = sig.strip() # Add in security token if we have one if token != '': params_with_headers['SecurityToken'] = token return params_with_headers
Sign a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L144-L181
[ "def creds(provider):\n '''\n Return the credentials for AWS signing. This could be just the id and key\n specified in the provider configuration, or if the id or key is set to the\n literal string 'use-instance-role-credentials' creds will pull the instance\n role credentials from the meta data, cache them, and provide them instead.\n '''\n # Declare globals\n global __AccessKeyId__, __SecretAccessKey__, __Token__, __Expiration__\n\n ret_credentials = ()\n\n # if id or key is 'use-instance-role-credentials', pull them from meta-data\n ## if needed\n if provider['id'] == IROLE_CODE or provider['key'] == IROLE_CODE:\n # Check to see if we have cache credentials that are still good\n if __Expiration__ != '':\n timenow = datetime.utcnow()\n timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ')\n if timestamp < __Expiration__:\n # Current timestamp less than expiration fo cached credentials\n return __AccessKeyId__, __SecretAccessKey__, __Token__\n # We don't have any cached credentials, or they are expired, get them\n\n # Connections to instance meta-data must fail fast and never be proxied\n try:\n result = requests.get(\n \"http://169.254.169.254/latest/meta-data/iam/security-credentials/\",\n proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT,\n )\n result.raise_for_status()\n role = result.text\n except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError):\n return provider['id'], provider['key'], ''\n\n try:\n result = requests.get(\n \"http://169.254.169.254/latest/meta-data/iam/security-credentials/{0}\".format(role),\n proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT,\n )\n result.raise_for_status()\n except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError):\n return provider['id'], provider['key'], ''\n\n data = result.json()\n __AccessKeyId__ = data['AccessKeyId']\n __SecretAccessKey__ = data['SecretAccessKey']\n __Token__ = data['Token']\n __Expiration__ = data['Expiration']\n\n ret_credentials = __AccessKeyId__, __SecretAccessKey__, __Token__\n else:\n ret_credentials = provider['id'], provider['key'], ''\n\n if provider.get('role_arn') is not None:\n provider_shadow = provider.copy()\n provider_shadow.pop(\"role_arn\", None)\n log.info(\"Assuming the role: %s\", provider.get('role_arn'))\n ret_credentials = assumed_creds(provider_shadow, role_arn=provider.get('role_arn'), location='us-east-1')\n\n return ret_credentials\n" ]
# -*- coding: utf-8 -*- ''' Connection library for AWS .. versionadded:: 2015.5.0 This is a base library used by a number of AWS services. :depends: requests ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import sys import time import binascii from datetime import datetime import hashlib import hmac import logging import salt.config import re import random from salt.ext import six # Import Salt libs import salt.utils.hashutils import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET # Import 3rd-party libs try: import requests HAS_REQUESTS = True # pylint: disable=W0612 except ImportError: HAS_REQUESTS = False # pylint: disable=W0612 # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, zip from salt.ext.six.moves.urllib.parse import urlencode, urlparse # pylint: enable=import-error,redefined-builtin,no-name-in-module log = logging.getLogger(__name__) DEFAULT_LOCATION = 'us-east-1' DEFAULT_AWS_API_VERSION = '2014-10-01' AWS_RETRY_CODES = [ 'RequestLimitExceeded', 'InsufficientInstanceCapacity', 'InternalError', 'Unavailable', 'InsufficientAddressCapacity', 'InsufficientReservedInstanceCapacity', ] AWS_METADATA_TIMEOUT = 3.05 AWS_MAX_RETRIES = 7 IROLE_CODE = 'use-instance-role-credentials' __AccessKeyId__ = '' __SecretAccessKey__ = '' __Token__ = '' __Expiration__ = '' __Location__ = '' __AssumeCache__ = {} def sleep_exponential_backoff(attempts): """ backoff an exponential amount of time to throttle requests during "API Rate Exceeded" failures as suggested by the AWS documentation here: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html and also here: https://docs.aws.amazon.com/general/latest/gr/api-retries.html Failure to implement this approach results in a failure rate of >30% when using salt-cloud with "--parallel" when creating 50 or more instances with a fixed delay of 2 seconds. A failure rate of >10% is observed when using the salt-api with an asynchronous client specified (runner_async). """ time.sleep(random.uniform(1, 2**attempts)) def creds(provider): ''' Return the credentials for AWS signing. This could be just the id and key specified in the provider configuration, or if the id or key is set to the literal string 'use-instance-role-credentials' creds will pull the instance role credentials from the meta data, cache them, and provide them instead. ''' # Declare globals global __AccessKeyId__, __SecretAccessKey__, __Token__, __Expiration__ ret_credentials = () # if id or key is 'use-instance-role-credentials', pull them from meta-data ## if needed if provider['id'] == IROLE_CODE or provider['key'] == IROLE_CODE: # Check to see if we have cache credentials that are still good if __Expiration__ != '': timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp < __Expiration__: # Current timestamp less than expiration fo cached credentials return __AccessKeyId__, __SecretAccessKey__, __Token__ # We don't have any cached credentials, or they are expired, get them # Connections to instance meta-data must fail fast and never be proxied try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() role = result.text except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/{0}".format(role), proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' data = result.json() __AccessKeyId__ = data['AccessKeyId'] __SecretAccessKey__ = data['SecretAccessKey'] __Token__ = data['Token'] __Expiration__ = data['Expiration'] ret_credentials = __AccessKeyId__, __SecretAccessKey__, __Token__ else: ret_credentials = provider['id'], provider['key'], '' if provider.get('role_arn') is not None: provider_shadow = provider.copy() provider_shadow.pop("role_arn", None) log.info("Assuming the role: %s", provider.get('role_arn')) ret_credentials = assumed_creds(provider_shadow, role_arn=provider.get('role_arn'), location='us-east-1') return ret_credentials def assumed_creds(prov_dict, role_arn, location=None): valid_session_name_re = re.compile("[^a-z0-9A-Z+=,.@-]") # current time in epoch seconds now = time.mktime(datetime.utcnow().timetuple()) for key, creds in __AssumeCache__.items(): if (creds["Expiration"] - now) <= 120: __AssumeCache__.delete(key) if role_arn in __AssumeCache__: c = __AssumeCache__[role_arn] return c["AccessKeyId"], c["SecretAccessKey"], c["SessionToken"] version = "2011-06-15" session_name = valid_session_name_re.sub('', salt.config.get_id({"root_dir": None})[0])[0:63] headers, requesturl = sig4( 'GET', 'sts.amazonaws.com', params={ "Version": version, "Action": "AssumeRole", "RoleSessionName": session_name, "RoleArn": role_arn, "Policy": '{"Version":"2012-10-17","Statement":[{"Sid":"Stmt1", "Effect":"Allow","Action":"*","Resource":"*"}]}', "DurationSeconds": "3600" }, aws_api_version=version, data='', uri='/', prov_dict=prov_dict, product='sts', location=location, requesturl="https://sts.amazonaws.com/" ) headers["Accept"] = "application/json" result = requests.request('GET', requesturl, headers=headers, data='', verify=True) if result.status_code >= 400: log.info('AssumeRole response: %s', result.content) result.raise_for_status() resp = result.json() data = resp["AssumeRoleResponse"]["AssumeRoleResult"]["Credentials"] __AssumeCache__[role_arn] = data return data["AccessKeyId"], data["SecretAccessKey"], data["SessionToken"] def sig4(method, endpoint, params, prov_dict, aws_api_version=DEFAULT_AWS_API_VERSION, location=None, product='ec2', uri='/', requesturl=None, data='', headers=None, role_arn=None, payload_hash=None): ''' Sign a query against AWS services using Signature Version 4 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html ''' timenow = datetime.utcnow() # Retrieve access credentials from meta-data, or use provided if role_arn is None: access_key_id, secret_access_key, token = creds(prov_dict) else: access_key_id, secret_access_key, token = assumed_creds(prov_dict, role_arn, location=location) if location is None: location = get_region_from_metadata() if location is None: location = DEFAULT_LOCATION params_with_headers = params.copy() if product not in ('s3', 'ssm'): params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(map(params_with_headers.get, keys)) querystring = urlencode(list(zip(keys, values))).replace('+', '%20') amzdate = timenow.strftime('%Y%m%dT%H%M%SZ') datestamp = timenow.strftime('%Y%m%d') new_headers = {} if isinstance(headers, dict): new_headers = headers.copy() # Create payload hash (hash of the request body content). For GET # requests, the payload is an empty string (''). if not payload_hash: payload_hash = salt.utils.hashutils.sha256_digest(data) new_headers['X-Amz-date'] = amzdate new_headers['host'] = endpoint new_headers['x-amz-content-sha256'] = payload_hash a_canonical_headers = [] a_signed_headers = [] if token != '': new_headers['X-Amz-security-token'] = token for header in sorted(new_headers.keys(), key=six.text_type.lower): lower_header = header.lower() a_canonical_headers.append('{0}:{1}'.format(lower_header, new_headers[header].strip())) a_signed_headers.append(lower_header) canonical_headers = '\n'.join(a_canonical_headers) + '\n' signed_headers = ';'.join(a_signed_headers) algorithm = 'AWS4-HMAC-SHA256' # Combine elements to create create canonical request canonical_request = '\n'.join(( method, uri, querystring, canonical_headers, signed_headers, payload_hash )) # Create the string to sign credential_scope = '/'.join((datestamp, location, product, 'aws4_request')) string_to_sign = '\n'.join(( algorithm, amzdate, credential_scope, salt.utils.hashutils.sha256_digest(canonical_request) )) # Create the signing key using the function defined above. signing_key = _sig_key( secret_access_key, datestamp, location, product ) # Sign the string_to_sign using the signing_key signature = hmac.new( signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest() # Add signing information to the request authorization_header = ( '{0} Credential={1}/{2}, SignedHeaders={3}, Signature={4}' ).format( algorithm, access_key_id, credential_scope, signed_headers, signature, ) new_headers['Authorization'] = authorization_header requesturl = '{0}?{1}'.format(requesturl, querystring) return new_headers, requesturl def _sign(key, msg): ''' Key derivation functions. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() def _sig_key(key, date_stamp, regionName, serviceName): ''' Get a signature key. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp) if regionName: kRegion = _sign(kDate, regionName) kService = _sign(kRegion, serviceName) else: kService = _sign(kDate, serviceName) kSigning = _sign(kService, 'aws4_request') return kSigning def query(params=None, setname=None, requesturl=None, location=None, return_url=False, return_root=False, opts=None, provider=None, endpoint=None, product='ec2', sigver='2'): ''' Perform a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html Regions and endpoints are documented at: http://docs.aws.amazon.com/general/latest/gr/rande.html Default ``product`` is ``ec2``. Valid ``product`` names are: .. code-block: yaml - autoscaling (Auto Scaling) - cloudformation (CloudFormation) - ec2 (Elastic Compute Cloud) - elasticache (ElastiCache) - elasticbeanstalk (Elastic BeanStalk) - elasticloadbalancing (Elastic Load Balancing) - elasticmapreduce (Elastic MapReduce) - iam (Identity and Access Management) - importexport (Import/Export) - monitoring (CloudWatch) - rds (Relational Database Service) - simpledb (SimpleDB) - sns (Simple Notification Service) - sqs (Simple Queue Service) ''' if params is None: params = {} if opts is None: opts = {} function = opts.get('function', (None, product)) providers = opts.get('providers', {}) if provider is None: prov_dict = providers.get(function[1], {}).get(product, {}) if prov_dict: driver = list(list(prov_dict.keys()))[0] provider = providers.get(driver, product) else: prov_dict = providers.get(provider, {}).get(product, {}) service_url = prov_dict.get('service_url', 'amazonaws.com') if not location: location = get_location(opts, prov_dict) if endpoint is None: if not requesturl: endpoint = prov_dict.get( 'endpoint', '{0}.{1}.{2}'.format(product, location, service_url) ) requesturl = 'https://{0}/'.format(endpoint) else: endpoint = urlparse(requesturl).netloc if endpoint == '': endpoint_err = ('Could not find a valid endpoint in the ' 'requesturl: {0}. Looking for something ' 'like https://some.aws.endpoint/?args').format( requesturl ) log.error(endpoint_err) if return_url is True: return {'error': endpoint_err}, requesturl return {'error': endpoint_err} log.debug('Using AWS endpoint: %s', endpoint) method = 'GET' aws_api_version = prov_dict.get( 'aws_api_version', prov_dict.get( '{0}_api_version'.format(product), DEFAULT_AWS_API_VERSION ) ) # Fallback to ec2's id & key if none is found, for this component if not prov_dict.get('id', None): prov_dict['id'] = providers.get(provider, {}).get('ec2', {}).get('id', {}) prov_dict['key'] = providers.get(provider, {}).get('ec2', {}).get('key', {}) if sigver == '4': headers, requesturl = sig4( method, endpoint, params, prov_dict, aws_api_version, location, product, requesturl=requesturl ) params_with_headers = {} else: params_with_headers = sig2( method, endpoint, params, prov_dict, aws_api_version ) headers = {} attempts = 0 while attempts < AWS_MAX_RETRIES: log.debug('AWS Request: %s', requesturl) log.trace('AWS Request Parameters: %s', params_with_headers) try: result = requests.get(requesturl, headers=headers, params=params_with_headers) log.debug('AWS Response Status Code: %s', result.status_code) log.trace( 'AWS Response Text: %s', result.text ) result.raise_for_status() break except requests.exceptions.HTTPError as exc: root = ET.fromstring(exc.response.content) data = xml.to_dict(root) # check to see if we should retry the query err_code = data.get('Errors', {}).get('Error', {}).get('Code', '') if attempts < AWS_MAX_RETRIES and err_code and err_code in AWS_RETRY_CODES: attempts += 1 log.error( 'AWS Response Status Code and Error: [%s %s] %s; ' 'Attempts remaining: %s', exc.response.status_code, exc, data, attempts ) sleep_exponential_backoff(attempts) continue log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} else: log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} root = ET.fromstring(result.text) items = root[1] if return_root is True: items = root if setname: if sys.version_info < (2, 7): children_len = len(root.getchildren()) else: children_len = len(root) for item in range(0, children_len): comps = root[item].tag.split('}') if comps[1] == setname: items = root[item] ret = [] for item in items: ret.append(xml.to_dict(item)) if return_url is True: return ret, requesturl return ret def get_region_from_metadata(): ''' Try to get region from instance identity document and cache it .. versionadded:: 2015.5.6 ''' global __Location__ if __Location__ == 'do-not-get-from-metadata': log.debug('Previously failed to get AWS region from metadata. Not trying again.') return None # Cached region if __Location__ != '': return __Location__ try: # Connections to instance meta-data must fail fast and never be proxied result = requests.get( "http://169.254.169.254/latest/dynamic/instance-identity/document", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) except requests.exceptions.RequestException: log.warning('Failed to get AWS region from instance metadata.', exc_info=True) # Do not try again __Location__ = 'do-not-get-from-metadata' return None try: region = result.json()['region'] __Location__ = region return __Location__ except (ValueError, KeyError): log.warning('Failed to decode JSON from instance metadata.') return None return None def get_location(opts=None, provider=None): ''' Return the region to use, in this order: opts['location'] provider['location'] get_region_from_metadata() DEFAULT_LOCATION ''' if opts is None: opts = {} ret = opts.get('location') if ret is None and provider is not None: ret = provider.get('location') if ret is None: ret = get_region_from_metadata() if ret is None: ret = DEFAULT_LOCATION return ret
saltstack/salt
salt/utils/aws.py
sig4
python
def sig4(method, endpoint, params, prov_dict, aws_api_version=DEFAULT_AWS_API_VERSION, location=None, product='ec2', uri='/', requesturl=None, data='', headers=None, role_arn=None, payload_hash=None): ''' Sign a query against AWS services using Signature Version 4 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html ''' timenow = datetime.utcnow() # Retrieve access credentials from meta-data, or use provided if role_arn is None: access_key_id, secret_access_key, token = creds(prov_dict) else: access_key_id, secret_access_key, token = assumed_creds(prov_dict, role_arn, location=location) if location is None: location = get_region_from_metadata() if location is None: location = DEFAULT_LOCATION params_with_headers = params.copy() if product not in ('s3', 'ssm'): params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(map(params_with_headers.get, keys)) querystring = urlencode(list(zip(keys, values))).replace('+', '%20') amzdate = timenow.strftime('%Y%m%dT%H%M%SZ') datestamp = timenow.strftime('%Y%m%d') new_headers = {} if isinstance(headers, dict): new_headers = headers.copy() # Create payload hash (hash of the request body content). For GET # requests, the payload is an empty string (''). if not payload_hash: payload_hash = salt.utils.hashutils.sha256_digest(data) new_headers['X-Amz-date'] = amzdate new_headers['host'] = endpoint new_headers['x-amz-content-sha256'] = payload_hash a_canonical_headers = [] a_signed_headers = [] if token != '': new_headers['X-Amz-security-token'] = token for header in sorted(new_headers.keys(), key=six.text_type.lower): lower_header = header.lower() a_canonical_headers.append('{0}:{1}'.format(lower_header, new_headers[header].strip())) a_signed_headers.append(lower_header) canonical_headers = '\n'.join(a_canonical_headers) + '\n' signed_headers = ';'.join(a_signed_headers) algorithm = 'AWS4-HMAC-SHA256' # Combine elements to create create canonical request canonical_request = '\n'.join(( method, uri, querystring, canonical_headers, signed_headers, payload_hash )) # Create the string to sign credential_scope = '/'.join((datestamp, location, product, 'aws4_request')) string_to_sign = '\n'.join(( algorithm, amzdate, credential_scope, salt.utils.hashutils.sha256_digest(canonical_request) )) # Create the signing key using the function defined above. signing_key = _sig_key( secret_access_key, datestamp, location, product ) # Sign the string_to_sign using the signing_key signature = hmac.new( signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest() # Add signing information to the request authorization_header = ( '{0} Credential={1}/{2}, SignedHeaders={3}, Signature={4}' ).format( algorithm, access_key_id, credential_scope, signed_headers, signature, ) new_headers['Authorization'] = authorization_header requesturl = '{0}?{1}'.format(requesturl, querystring) return new_headers, requesturl
Sign a query against AWS services using Signature Version 4 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L235-L343
[ "def creds(provider):\n '''\n Return the credentials for AWS signing. This could be just the id and key\n specified in the provider configuration, or if the id or key is set to the\n literal string 'use-instance-role-credentials' creds will pull the instance\n role credentials from the meta data, cache them, and provide them instead.\n '''\n # Declare globals\n global __AccessKeyId__, __SecretAccessKey__, __Token__, __Expiration__\n\n ret_credentials = ()\n\n # if id or key is 'use-instance-role-credentials', pull them from meta-data\n ## if needed\n if provider['id'] == IROLE_CODE or provider['key'] == IROLE_CODE:\n # Check to see if we have cache credentials that are still good\n if __Expiration__ != '':\n timenow = datetime.utcnow()\n timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ')\n if timestamp < __Expiration__:\n # Current timestamp less than expiration fo cached credentials\n return __AccessKeyId__, __SecretAccessKey__, __Token__\n # We don't have any cached credentials, or they are expired, get them\n\n # Connections to instance meta-data must fail fast and never be proxied\n try:\n result = requests.get(\n \"http://169.254.169.254/latest/meta-data/iam/security-credentials/\",\n proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT,\n )\n result.raise_for_status()\n role = result.text\n except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError):\n return provider['id'], provider['key'], ''\n\n try:\n result = requests.get(\n \"http://169.254.169.254/latest/meta-data/iam/security-credentials/{0}\".format(role),\n proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT,\n )\n result.raise_for_status()\n except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError):\n return provider['id'], provider['key'], ''\n\n data = result.json()\n __AccessKeyId__ = data['AccessKeyId']\n __SecretAccessKey__ = data['SecretAccessKey']\n __Token__ = data['Token']\n __Expiration__ = data['Expiration']\n\n ret_credentials = __AccessKeyId__, __SecretAccessKey__, __Token__\n else:\n ret_credentials = provider['id'], provider['key'], ''\n\n if provider.get('role_arn') is not None:\n provider_shadow = provider.copy()\n provider_shadow.pop(\"role_arn\", None)\n log.info(\"Assuming the role: %s\", provider.get('role_arn'))\n ret_credentials = assumed_creds(provider_shadow, role_arn=provider.get('role_arn'), location='us-east-1')\n\n return ret_credentials\n", "def assumed_creds(prov_dict, role_arn, location=None):\n valid_session_name_re = re.compile(\"[^a-z0-9A-Z+=,.@-]\")\n\n # current time in epoch seconds\n now = time.mktime(datetime.utcnow().timetuple())\n\n for key, creds in __AssumeCache__.items():\n if (creds[\"Expiration\"] - now) <= 120:\n __AssumeCache__.delete(key)\n\n if role_arn in __AssumeCache__:\n c = __AssumeCache__[role_arn]\n return c[\"AccessKeyId\"], c[\"SecretAccessKey\"], c[\"SessionToken\"]\n\n version = \"2011-06-15\"\n session_name = valid_session_name_re.sub('', salt.config.get_id({\"root_dir\": None})[0])[0:63]\n\n headers, requesturl = sig4(\n 'GET',\n 'sts.amazonaws.com',\n params={\n \"Version\": version,\n \"Action\": \"AssumeRole\",\n \"RoleSessionName\": session_name,\n \"RoleArn\": role_arn,\n \"Policy\": '{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\", \"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}',\n \"DurationSeconds\": \"3600\"\n },\n aws_api_version=version,\n data='',\n uri='/',\n prov_dict=prov_dict,\n product='sts',\n location=location,\n requesturl=\"https://sts.amazonaws.com/\"\n )\n headers[\"Accept\"] = \"application/json\"\n result = requests.request('GET', requesturl, headers=headers,\n data='',\n verify=True)\n\n if result.status_code >= 400:\n log.info('AssumeRole response: %s', result.content)\n result.raise_for_status()\n resp = result.json()\n\n data = resp[\"AssumeRoleResponse\"][\"AssumeRoleResult\"][\"Credentials\"]\n __AssumeCache__[role_arn] = data\n return data[\"AccessKeyId\"], data[\"SecretAccessKey\"], data[\"SessionToken\"]\n", "def get_region_from_metadata():\n '''\n Try to get region from instance identity document and cache it\n\n .. versionadded:: 2015.5.6\n '''\n global __Location__\n\n if __Location__ == 'do-not-get-from-metadata':\n log.debug('Previously failed to get AWS region from metadata. Not trying again.')\n return None\n\n # Cached region\n if __Location__ != '':\n return __Location__\n\n try:\n # Connections to instance meta-data must fail fast and never be proxied\n result = requests.get(\n \"http://169.254.169.254/latest/dynamic/instance-identity/document\",\n proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT,\n )\n except requests.exceptions.RequestException:\n log.warning('Failed to get AWS region from instance metadata.', exc_info=True)\n # Do not try again\n __Location__ = 'do-not-get-from-metadata'\n return None\n\n try:\n region = result.json()['region']\n __Location__ = region\n return __Location__\n except (ValueError, KeyError):\n log.warning('Failed to decode JSON from instance metadata.')\n return None\n\n return None\n", "def _sig_key(key, date_stamp, regionName, serviceName):\n '''\n Get a signature key. See:\n\n http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python\n '''\n kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp)\n if regionName:\n kRegion = _sign(kDate, regionName)\n kService = _sign(kRegion, serviceName)\n else:\n kService = _sign(kDate, serviceName)\n kSigning = _sign(kService, 'aws4_request')\n return kSigning\n" ]
# -*- coding: utf-8 -*- ''' Connection library for AWS .. versionadded:: 2015.5.0 This is a base library used by a number of AWS services. :depends: requests ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import sys import time import binascii from datetime import datetime import hashlib import hmac import logging import salt.config import re import random from salt.ext import six # Import Salt libs import salt.utils.hashutils import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET # Import 3rd-party libs try: import requests HAS_REQUESTS = True # pylint: disable=W0612 except ImportError: HAS_REQUESTS = False # pylint: disable=W0612 # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, zip from salt.ext.six.moves.urllib.parse import urlencode, urlparse # pylint: enable=import-error,redefined-builtin,no-name-in-module log = logging.getLogger(__name__) DEFAULT_LOCATION = 'us-east-1' DEFAULT_AWS_API_VERSION = '2014-10-01' AWS_RETRY_CODES = [ 'RequestLimitExceeded', 'InsufficientInstanceCapacity', 'InternalError', 'Unavailable', 'InsufficientAddressCapacity', 'InsufficientReservedInstanceCapacity', ] AWS_METADATA_TIMEOUT = 3.05 AWS_MAX_RETRIES = 7 IROLE_CODE = 'use-instance-role-credentials' __AccessKeyId__ = '' __SecretAccessKey__ = '' __Token__ = '' __Expiration__ = '' __Location__ = '' __AssumeCache__ = {} def sleep_exponential_backoff(attempts): """ backoff an exponential amount of time to throttle requests during "API Rate Exceeded" failures as suggested by the AWS documentation here: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html and also here: https://docs.aws.amazon.com/general/latest/gr/api-retries.html Failure to implement this approach results in a failure rate of >30% when using salt-cloud with "--parallel" when creating 50 or more instances with a fixed delay of 2 seconds. A failure rate of >10% is observed when using the salt-api with an asynchronous client specified (runner_async). """ time.sleep(random.uniform(1, 2**attempts)) def creds(provider): ''' Return the credentials for AWS signing. This could be just the id and key specified in the provider configuration, or if the id or key is set to the literal string 'use-instance-role-credentials' creds will pull the instance role credentials from the meta data, cache them, and provide them instead. ''' # Declare globals global __AccessKeyId__, __SecretAccessKey__, __Token__, __Expiration__ ret_credentials = () # if id or key is 'use-instance-role-credentials', pull them from meta-data ## if needed if provider['id'] == IROLE_CODE or provider['key'] == IROLE_CODE: # Check to see if we have cache credentials that are still good if __Expiration__ != '': timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp < __Expiration__: # Current timestamp less than expiration fo cached credentials return __AccessKeyId__, __SecretAccessKey__, __Token__ # We don't have any cached credentials, or they are expired, get them # Connections to instance meta-data must fail fast and never be proxied try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() role = result.text except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/{0}".format(role), proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' data = result.json() __AccessKeyId__ = data['AccessKeyId'] __SecretAccessKey__ = data['SecretAccessKey'] __Token__ = data['Token'] __Expiration__ = data['Expiration'] ret_credentials = __AccessKeyId__, __SecretAccessKey__, __Token__ else: ret_credentials = provider['id'], provider['key'], '' if provider.get('role_arn') is not None: provider_shadow = provider.copy() provider_shadow.pop("role_arn", None) log.info("Assuming the role: %s", provider.get('role_arn')) ret_credentials = assumed_creds(provider_shadow, role_arn=provider.get('role_arn'), location='us-east-1') return ret_credentials def sig2(method, endpoint, params, provider, aws_api_version): ''' Sign a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html ''' timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') # Retrieve access credentials from meta-data, or use provided access_key_id, secret_access_key, token = creds(provider) params_with_headers = params.copy() params_with_headers['AWSAccessKeyId'] = access_key_id params_with_headers['SignatureVersion'] = '2' params_with_headers['SignatureMethod'] = 'HmacSHA256' params_with_headers['Timestamp'] = '{0}'.format(timestamp) params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(list(map(params_with_headers.get, keys))) querystring = urlencode(list(zip(keys, values))) canonical = '{0}\n{1}\n/\n{2}'.format( method.encode('utf-8'), endpoint.encode('utf-8'), querystring.encode('utf-8'), ) hashed = hmac.new(secret_access_key, canonical, hashlib.sha256) sig = binascii.b2a_base64(hashed.digest()) params_with_headers['Signature'] = sig.strip() # Add in security token if we have one if token != '': params_with_headers['SecurityToken'] = token return params_with_headers def assumed_creds(prov_dict, role_arn, location=None): valid_session_name_re = re.compile("[^a-z0-9A-Z+=,.@-]") # current time in epoch seconds now = time.mktime(datetime.utcnow().timetuple()) for key, creds in __AssumeCache__.items(): if (creds["Expiration"] - now) <= 120: __AssumeCache__.delete(key) if role_arn in __AssumeCache__: c = __AssumeCache__[role_arn] return c["AccessKeyId"], c["SecretAccessKey"], c["SessionToken"] version = "2011-06-15" session_name = valid_session_name_re.sub('', salt.config.get_id({"root_dir": None})[0])[0:63] headers, requesturl = sig4( 'GET', 'sts.amazonaws.com', params={ "Version": version, "Action": "AssumeRole", "RoleSessionName": session_name, "RoleArn": role_arn, "Policy": '{"Version":"2012-10-17","Statement":[{"Sid":"Stmt1", "Effect":"Allow","Action":"*","Resource":"*"}]}', "DurationSeconds": "3600" }, aws_api_version=version, data='', uri='/', prov_dict=prov_dict, product='sts', location=location, requesturl="https://sts.amazonaws.com/" ) headers["Accept"] = "application/json" result = requests.request('GET', requesturl, headers=headers, data='', verify=True) if result.status_code >= 400: log.info('AssumeRole response: %s', result.content) result.raise_for_status() resp = result.json() data = resp["AssumeRoleResponse"]["AssumeRoleResult"]["Credentials"] __AssumeCache__[role_arn] = data return data["AccessKeyId"], data["SecretAccessKey"], data["SessionToken"] def _sign(key, msg): ''' Key derivation functions. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() def _sig_key(key, date_stamp, regionName, serviceName): ''' Get a signature key. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp) if regionName: kRegion = _sign(kDate, regionName) kService = _sign(kRegion, serviceName) else: kService = _sign(kDate, serviceName) kSigning = _sign(kService, 'aws4_request') return kSigning def query(params=None, setname=None, requesturl=None, location=None, return_url=False, return_root=False, opts=None, provider=None, endpoint=None, product='ec2', sigver='2'): ''' Perform a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html Regions and endpoints are documented at: http://docs.aws.amazon.com/general/latest/gr/rande.html Default ``product`` is ``ec2``. Valid ``product`` names are: .. code-block: yaml - autoscaling (Auto Scaling) - cloudformation (CloudFormation) - ec2 (Elastic Compute Cloud) - elasticache (ElastiCache) - elasticbeanstalk (Elastic BeanStalk) - elasticloadbalancing (Elastic Load Balancing) - elasticmapreduce (Elastic MapReduce) - iam (Identity and Access Management) - importexport (Import/Export) - monitoring (CloudWatch) - rds (Relational Database Service) - simpledb (SimpleDB) - sns (Simple Notification Service) - sqs (Simple Queue Service) ''' if params is None: params = {} if opts is None: opts = {} function = opts.get('function', (None, product)) providers = opts.get('providers', {}) if provider is None: prov_dict = providers.get(function[1], {}).get(product, {}) if prov_dict: driver = list(list(prov_dict.keys()))[0] provider = providers.get(driver, product) else: prov_dict = providers.get(provider, {}).get(product, {}) service_url = prov_dict.get('service_url', 'amazonaws.com') if not location: location = get_location(opts, prov_dict) if endpoint is None: if not requesturl: endpoint = prov_dict.get( 'endpoint', '{0}.{1}.{2}'.format(product, location, service_url) ) requesturl = 'https://{0}/'.format(endpoint) else: endpoint = urlparse(requesturl).netloc if endpoint == '': endpoint_err = ('Could not find a valid endpoint in the ' 'requesturl: {0}. Looking for something ' 'like https://some.aws.endpoint/?args').format( requesturl ) log.error(endpoint_err) if return_url is True: return {'error': endpoint_err}, requesturl return {'error': endpoint_err} log.debug('Using AWS endpoint: %s', endpoint) method = 'GET' aws_api_version = prov_dict.get( 'aws_api_version', prov_dict.get( '{0}_api_version'.format(product), DEFAULT_AWS_API_VERSION ) ) # Fallback to ec2's id & key if none is found, for this component if not prov_dict.get('id', None): prov_dict['id'] = providers.get(provider, {}).get('ec2', {}).get('id', {}) prov_dict['key'] = providers.get(provider, {}).get('ec2', {}).get('key', {}) if sigver == '4': headers, requesturl = sig4( method, endpoint, params, prov_dict, aws_api_version, location, product, requesturl=requesturl ) params_with_headers = {} else: params_with_headers = sig2( method, endpoint, params, prov_dict, aws_api_version ) headers = {} attempts = 0 while attempts < AWS_MAX_RETRIES: log.debug('AWS Request: %s', requesturl) log.trace('AWS Request Parameters: %s', params_with_headers) try: result = requests.get(requesturl, headers=headers, params=params_with_headers) log.debug('AWS Response Status Code: %s', result.status_code) log.trace( 'AWS Response Text: %s', result.text ) result.raise_for_status() break except requests.exceptions.HTTPError as exc: root = ET.fromstring(exc.response.content) data = xml.to_dict(root) # check to see if we should retry the query err_code = data.get('Errors', {}).get('Error', {}).get('Code', '') if attempts < AWS_MAX_RETRIES and err_code and err_code in AWS_RETRY_CODES: attempts += 1 log.error( 'AWS Response Status Code and Error: [%s %s] %s; ' 'Attempts remaining: %s', exc.response.status_code, exc, data, attempts ) sleep_exponential_backoff(attempts) continue log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} else: log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} root = ET.fromstring(result.text) items = root[1] if return_root is True: items = root if setname: if sys.version_info < (2, 7): children_len = len(root.getchildren()) else: children_len = len(root) for item in range(0, children_len): comps = root[item].tag.split('}') if comps[1] == setname: items = root[item] ret = [] for item in items: ret.append(xml.to_dict(item)) if return_url is True: return ret, requesturl return ret def get_region_from_metadata(): ''' Try to get region from instance identity document and cache it .. versionadded:: 2015.5.6 ''' global __Location__ if __Location__ == 'do-not-get-from-metadata': log.debug('Previously failed to get AWS region from metadata. Not trying again.') return None # Cached region if __Location__ != '': return __Location__ try: # Connections to instance meta-data must fail fast and never be proxied result = requests.get( "http://169.254.169.254/latest/dynamic/instance-identity/document", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) except requests.exceptions.RequestException: log.warning('Failed to get AWS region from instance metadata.', exc_info=True) # Do not try again __Location__ = 'do-not-get-from-metadata' return None try: region = result.json()['region'] __Location__ = region return __Location__ except (ValueError, KeyError): log.warning('Failed to decode JSON from instance metadata.') return None return None def get_location(opts=None, provider=None): ''' Return the region to use, in this order: opts['location'] provider['location'] get_region_from_metadata() DEFAULT_LOCATION ''' if opts is None: opts = {} ret = opts.get('location') if ret is None and provider is not None: ret = provider.get('location') if ret is None: ret = get_region_from_metadata() if ret is None: ret = DEFAULT_LOCATION return ret
saltstack/salt
salt/utils/aws.py
_sig_key
python
def _sig_key(key, date_stamp, regionName, serviceName): ''' Get a signature key. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp) if regionName: kRegion = _sign(kDate, regionName) kService = _sign(kRegion, serviceName) else: kService = _sign(kDate, serviceName) kSigning = _sign(kService, 'aws4_request') return kSigning
Get a signature key. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L355-L368
null
# -*- coding: utf-8 -*- ''' Connection library for AWS .. versionadded:: 2015.5.0 This is a base library used by a number of AWS services. :depends: requests ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import sys import time import binascii from datetime import datetime import hashlib import hmac import logging import salt.config import re import random from salt.ext import six # Import Salt libs import salt.utils.hashutils import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET # Import 3rd-party libs try: import requests HAS_REQUESTS = True # pylint: disable=W0612 except ImportError: HAS_REQUESTS = False # pylint: disable=W0612 # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, zip from salt.ext.six.moves.urllib.parse import urlencode, urlparse # pylint: enable=import-error,redefined-builtin,no-name-in-module log = logging.getLogger(__name__) DEFAULT_LOCATION = 'us-east-1' DEFAULT_AWS_API_VERSION = '2014-10-01' AWS_RETRY_CODES = [ 'RequestLimitExceeded', 'InsufficientInstanceCapacity', 'InternalError', 'Unavailable', 'InsufficientAddressCapacity', 'InsufficientReservedInstanceCapacity', ] AWS_METADATA_TIMEOUT = 3.05 AWS_MAX_RETRIES = 7 IROLE_CODE = 'use-instance-role-credentials' __AccessKeyId__ = '' __SecretAccessKey__ = '' __Token__ = '' __Expiration__ = '' __Location__ = '' __AssumeCache__ = {} def sleep_exponential_backoff(attempts): """ backoff an exponential amount of time to throttle requests during "API Rate Exceeded" failures as suggested by the AWS documentation here: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html and also here: https://docs.aws.amazon.com/general/latest/gr/api-retries.html Failure to implement this approach results in a failure rate of >30% when using salt-cloud with "--parallel" when creating 50 or more instances with a fixed delay of 2 seconds. A failure rate of >10% is observed when using the salt-api with an asynchronous client specified (runner_async). """ time.sleep(random.uniform(1, 2**attempts)) def creds(provider): ''' Return the credentials for AWS signing. This could be just the id and key specified in the provider configuration, or if the id or key is set to the literal string 'use-instance-role-credentials' creds will pull the instance role credentials from the meta data, cache them, and provide them instead. ''' # Declare globals global __AccessKeyId__, __SecretAccessKey__, __Token__, __Expiration__ ret_credentials = () # if id or key is 'use-instance-role-credentials', pull them from meta-data ## if needed if provider['id'] == IROLE_CODE or provider['key'] == IROLE_CODE: # Check to see if we have cache credentials that are still good if __Expiration__ != '': timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp < __Expiration__: # Current timestamp less than expiration fo cached credentials return __AccessKeyId__, __SecretAccessKey__, __Token__ # We don't have any cached credentials, or they are expired, get them # Connections to instance meta-data must fail fast and never be proxied try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() role = result.text except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/{0}".format(role), proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' data = result.json() __AccessKeyId__ = data['AccessKeyId'] __SecretAccessKey__ = data['SecretAccessKey'] __Token__ = data['Token'] __Expiration__ = data['Expiration'] ret_credentials = __AccessKeyId__, __SecretAccessKey__, __Token__ else: ret_credentials = provider['id'], provider['key'], '' if provider.get('role_arn') is not None: provider_shadow = provider.copy() provider_shadow.pop("role_arn", None) log.info("Assuming the role: %s", provider.get('role_arn')) ret_credentials = assumed_creds(provider_shadow, role_arn=provider.get('role_arn'), location='us-east-1') return ret_credentials def sig2(method, endpoint, params, provider, aws_api_version): ''' Sign a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html ''' timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') # Retrieve access credentials from meta-data, or use provided access_key_id, secret_access_key, token = creds(provider) params_with_headers = params.copy() params_with_headers['AWSAccessKeyId'] = access_key_id params_with_headers['SignatureVersion'] = '2' params_with_headers['SignatureMethod'] = 'HmacSHA256' params_with_headers['Timestamp'] = '{0}'.format(timestamp) params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(list(map(params_with_headers.get, keys))) querystring = urlencode(list(zip(keys, values))) canonical = '{0}\n{1}\n/\n{2}'.format( method.encode('utf-8'), endpoint.encode('utf-8'), querystring.encode('utf-8'), ) hashed = hmac.new(secret_access_key, canonical, hashlib.sha256) sig = binascii.b2a_base64(hashed.digest()) params_with_headers['Signature'] = sig.strip() # Add in security token if we have one if token != '': params_with_headers['SecurityToken'] = token return params_with_headers def assumed_creds(prov_dict, role_arn, location=None): valid_session_name_re = re.compile("[^a-z0-9A-Z+=,.@-]") # current time in epoch seconds now = time.mktime(datetime.utcnow().timetuple()) for key, creds in __AssumeCache__.items(): if (creds["Expiration"] - now) <= 120: __AssumeCache__.delete(key) if role_arn in __AssumeCache__: c = __AssumeCache__[role_arn] return c["AccessKeyId"], c["SecretAccessKey"], c["SessionToken"] version = "2011-06-15" session_name = valid_session_name_re.sub('', salt.config.get_id({"root_dir": None})[0])[0:63] headers, requesturl = sig4( 'GET', 'sts.amazonaws.com', params={ "Version": version, "Action": "AssumeRole", "RoleSessionName": session_name, "RoleArn": role_arn, "Policy": '{"Version":"2012-10-17","Statement":[{"Sid":"Stmt1", "Effect":"Allow","Action":"*","Resource":"*"}]}', "DurationSeconds": "3600" }, aws_api_version=version, data='', uri='/', prov_dict=prov_dict, product='sts', location=location, requesturl="https://sts.amazonaws.com/" ) headers["Accept"] = "application/json" result = requests.request('GET', requesturl, headers=headers, data='', verify=True) if result.status_code >= 400: log.info('AssumeRole response: %s', result.content) result.raise_for_status() resp = result.json() data = resp["AssumeRoleResponse"]["AssumeRoleResult"]["Credentials"] __AssumeCache__[role_arn] = data return data["AccessKeyId"], data["SecretAccessKey"], data["SessionToken"] def sig4(method, endpoint, params, prov_dict, aws_api_version=DEFAULT_AWS_API_VERSION, location=None, product='ec2', uri='/', requesturl=None, data='', headers=None, role_arn=None, payload_hash=None): ''' Sign a query against AWS services using Signature Version 4 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html ''' timenow = datetime.utcnow() # Retrieve access credentials from meta-data, or use provided if role_arn is None: access_key_id, secret_access_key, token = creds(prov_dict) else: access_key_id, secret_access_key, token = assumed_creds(prov_dict, role_arn, location=location) if location is None: location = get_region_from_metadata() if location is None: location = DEFAULT_LOCATION params_with_headers = params.copy() if product not in ('s3', 'ssm'): params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(map(params_with_headers.get, keys)) querystring = urlencode(list(zip(keys, values))).replace('+', '%20') amzdate = timenow.strftime('%Y%m%dT%H%M%SZ') datestamp = timenow.strftime('%Y%m%d') new_headers = {} if isinstance(headers, dict): new_headers = headers.copy() # Create payload hash (hash of the request body content). For GET # requests, the payload is an empty string (''). if not payload_hash: payload_hash = salt.utils.hashutils.sha256_digest(data) new_headers['X-Amz-date'] = amzdate new_headers['host'] = endpoint new_headers['x-amz-content-sha256'] = payload_hash a_canonical_headers = [] a_signed_headers = [] if token != '': new_headers['X-Amz-security-token'] = token for header in sorted(new_headers.keys(), key=six.text_type.lower): lower_header = header.lower() a_canonical_headers.append('{0}:{1}'.format(lower_header, new_headers[header].strip())) a_signed_headers.append(lower_header) canonical_headers = '\n'.join(a_canonical_headers) + '\n' signed_headers = ';'.join(a_signed_headers) algorithm = 'AWS4-HMAC-SHA256' # Combine elements to create create canonical request canonical_request = '\n'.join(( method, uri, querystring, canonical_headers, signed_headers, payload_hash )) # Create the string to sign credential_scope = '/'.join((datestamp, location, product, 'aws4_request')) string_to_sign = '\n'.join(( algorithm, amzdate, credential_scope, salt.utils.hashutils.sha256_digest(canonical_request) )) # Create the signing key using the function defined above. signing_key = _sig_key( secret_access_key, datestamp, location, product ) # Sign the string_to_sign using the signing_key signature = hmac.new( signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest() # Add signing information to the request authorization_header = ( '{0} Credential={1}/{2}, SignedHeaders={3}, Signature={4}' ).format( algorithm, access_key_id, credential_scope, signed_headers, signature, ) new_headers['Authorization'] = authorization_header requesturl = '{0}?{1}'.format(requesturl, querystring) return new_headers, requesturl def _sign(key, msg): ''' Key derivation functions. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() def query(params=None, setname=None, requesturl=None, location=None, return_url=False, return_root=False, opts=None, provider=None, endpoint=None, product='ec2', sigver='2'): ''' Perform a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html Regions and endpoints are documented at: http://docs.aws.amazon.com/general/latest/gr/rande.html Default ``product`` is ``ec2``. Valid ``product`` names are: .. code-block: yaml - autoscaling (Auto Scaling) - cloudformation (CloudFormation) - ec2 (Elastic Compute Cloud) - elasticache (ElastiCache) - elasticbeanstalk (Elastic BeanStalk) - elasticloadbalancing (Elastic Load Balancing) - elasticmapreduce (Elastic MapReduce) - iam (Identity and Access Management) - importexport (Import/Export) - monitoring (CloudWatch) - rds (Relational Database Service) - simpledb (SimpleDB) - sns (Simple Notification Service) - sqs (Simple Queue Service) ''' if params is None: params = {} if opts is None: opts = {} function = opts.get('function', (None, product)) providers = opts.get('providers', {}) if provider is None: prov_dict = providers.get(function[1], {}).get(product, {}) if prov_dict: driver = list(list(prov_dict.keys()))[0] provider = providers.get(driver, product) else: prov_dict = providers.get(provider, {}).get(product, {}) service_url = prov_dict.get('service_url', 'amazonaws.com') if not location: location = get_location(opts, prov_dict) if endpoint is None: if not requesturl: endpoint = prov_dict.get( 'endpoint', '{0}.{1}.{2}'.format(product, location, service_url) ) requesturl = 'https://{0}/'.format(endpoint) else: endpoint = urlparse(requesturl).netloc if endpoint == '': endpoint_err = ('Could not find a valid endpoint in the ' 'requesturl: {0}. Looking for something ' 'like https://some.aws.endpoint/?args').format( requesturl ) log.error(endpoint_err) if return_url is True: return {'error': endpoint_err}, requesturl return {'error': endpoint_err} log.debug('Using AWS endpoint: %s', endpoint) method = 'GET' aws_api_version = prov_dict.get( 'aws_api_version', prov_dict.get( '{0}_api_version'.format(product), DEFAULT_AWS_API_VERSION ) ) # Fallback to ec2's id & key if none is found, for this component if not prov_dict.get('id', None): prov_dict['id'] = providers.get(provider, {}).get('ec2', {}).get('id', {}) prov_dict['key'] = providers.get(provider, {}).get('ec2', {}).get('key', {}) if sigver == '4': headers, requesturl = sig4( method, endpoint, params, prov_dict, aws_api_version, location, product, requesturl=requesturl ) params_with_headers = {} else: params_with_headers = sig2( method, endpoint, params, prov_dict, aws_api_version ) headers = {} attempts = 0 while attempts < AWS_MAX_RETRIES: log.debug('AWS Request: %s', requesturl) log.trace('AWS Request Parameters: %s', params_with_headers) try: result = requests.get(requesturl, headers=headers, params=params_with_headers) log.debug('AWS Response Status Code: %s', result.status_code) log.trace( 'AWS Response Text: %s', result.text ) result.raise_for_status() break except requests.exceptions.HTTPError as exc: root = ET.fromstring(exc.response.content) data = xml.to_dict(root) # check to see if we should retry the query err_code = data.get('Errors', {}).get('Error', {}).get('Code', '') if attempts < AWS_MAX_RETRIES and err_code and err_code in AWS_RETRY_CODES: attempts += 1 log.error( 'AWS Response Status Code and Error: [%s %s] %s; ' 'Attempts remaining: %s', exc.response.status_code, exc, data, attempts ) sleep_exponential_backoff(attempts) continue log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} else: log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} root = ET.fromstring(result.text) items = root[1] if return_root is True: items = root if setname: if sys.version_info < (2, 7): children_len = len(root.getchildren()) else: children_len = len(root) for item in range(0, children_len): comps = root[item].tag.split('}') if comps[1] == setname: items = root[item] ret = [] for item in items: ret.append(xml.to_dict(item)) if return_url is True: return ret, requesturl return ret def get_region_from_metadata(): ''' Try to get region from instance identity document and cache it .. versionadded:: 2015.5.6 ''' global __Location__ if __Location__ == 'do-not-get-from-metadata': log.debug('Previously failed to get AWS region from metadata. Not trying again.') return None # Cached region if __Location__ != '': return __Location__ try: # Connections to instance meta-data must fail fast and never be proxied result = requests.get( "http://169.254.169.254/latest/dynamic/instance-identity/document", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) except requests.exceptions.RequestException: log.warning('Failed to get AWS region from instance metadata.', exc_info=True) # Do not try again __Location__ = 'do-not-get-from-metadata' return None try: region = result.json()['region'] __Location__ = region return __Location__ except (ValueError, KeyError): log.warning('Failed to decode JSON from instance metadata.') return None return None def get_location(opts=None, provider=None): ''' Return the region to use, in this order: opts['location'] provider['location'] get_region_from_metadata() DEFAULT_LOCATION ''' if opts is None: opts = {} ret = opts.get('location') if ret is None and provider is not None: ret = provider.get('location') if ret is None: ret = get_region_from_metadata() if ret is None: ret = DEFAULT_LOCATION return ret
saltstack/salt
salt/utils/aws.py
query
python
def query(params=None, setname=None, requesturl=None, location=None, return_url=False, return_root=False, opts=None, provider=None, endpoint=None, product='ec2', sigver='2'): ''' Perform a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html Regions and endpoints are documented at: http://docs.aws.amazon.com/general/latest/gr/rande.html Default ``product`` is ``ec2``. Valid ``product`` names are: .. code-block: yaml - autoscaling (Auto Scaling) - cloudformation (CloudFormation) - ec2 (Elastic Compute Cloud) - elasticache (ElastiCache) - elasticbeanstalk (Elastic BeanStalk) - elasticloadbalancing (Elastic Load Balancing) - elasticmapreduce (Elastic MapReduce) - iam (Identity and Access Management) - importexport (Import/Export) - monitoring (CloudWatch) - rds (Relational Database Service) - simpledb (SimpleDB) - sns (Simple Notification Service) - sqs (Simple Queue Service) ''' if params is None: params = {} if opts is None: opts = {} function = opts.get('function', (None, product)) providers = opts.get('providers', {}) if provider is None: prov_dict = providers.get(function[1], {}).get(product, {}) if prov_dict: driver = list(list(prov_dict.keys()))[0] provider = providers.get(driver, product) else: prov_dict = providers.get(provider, {}).get(product, {}) service_url = prov_dict.get('service_url', 'amazonaws.com') if not location: location = get_location(opts, prov_dict) if endpoint is None: if not requesturl: endpoint = prov_dict.get( 'endpoint', '{0}.{1}.{2}'.format(product, location, service_url) ) requesturl = 'https://{0}/'.format(endpoint) else: endpoint = urlparse(requesturl).netloc if endpoint == '': endpoint_err = ('Could not find a valid endpoint in the ' 'requesturl: {0}. Looking for something ' 'like https://some.aws.endpoint/?args').format( requesturl ) log.error(endpoint_err) if return_url is True: return {'error': endpoint_err}, requesturl return {'error': endpoint_err} log.debug('Using AWS endpoint: %s', endpoint) method = 'GET' aws_api_version = prov_dict.get( 'aws_api_version', prov_dict.get( '{0}_api_version'.format(product), DEFAULT_AWS_API_VERSION ) ) # Fallback to ec2's id & key if none is found, for this component if not prov_dict.get('id', None): prov_dict['id'] = providers.get(provider, {}).get('ec2', {}).get('id', {}) prov_dict['key'] = providers.get(provider, {}).get('ec2', {}).get('key', {}) if sigver == '4': headers, requesturl = sig4( method, endpoint, params, prov_dict, aws_api_version, location, product, requesturl=requesturl ) params_with_headers = {} else: params_with_headers = sig2( method, endpoint, params, prov_dict, aws_api_version ) headers = {} attempts = 0 while attempts < AWS_MAX_RETRIES: log.debug('AWS Request: %s', requesturl) log.trace('AWS Request Parameters: %s', params_with_headers) try: result = requests.get(requesturl, headers=headers, params=params_with_headers) log.debug('AWS Response Status Code: %s', result.status_code) log.trace( 'AWS Response Text: %s', result.text ) result.raise_for_status() break except requests.exceptions.HTTPError as exc: root = ET.fromstring(exc.response.content) data = xml.to_dict(root) # check to see if we should retry the query err_code = data.get('Errors', {}).get('Error', {}).get('Code', '') if attempts < AWS_MAX_RETRIES and err_code and err_code in AWS_RETRY_CODES: attempts += 1 log.error( 'AWS Response Status Code and Error: [%s %s] %s; ' 'Attempts remaining: %s', exc.response.status_code, exc, data, attempts ) sleep_exponential_backoff(attempts) continue log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} else: log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} root = ET.fromstring(result.text) items = root[1] if return_root is True: items = root if setname: if sys.version_info < (2, 7): children_len = len(root.getchildren()) else: children_len = len(root) for item in range(0, children_len): comps = root[item].tag.split('}') if comps[1] == setname: items = root[item] ret = [] for item in items: ret.append(xml.to_dict(item)) if return_url is True: return ret, requesturl return ret
Perform a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html Regions and endpoints are documented at: http://docs.aws.amazon.com/general/latest/gr/rande.html Default ``product`` is ``ec2``. Valid ``product`` names are: .. code-block: yaml - autoscaling (Auto Scaling) - cloudformation (CloudFormation) - ec2 (Elastic Compute Cloud) - elasticache (ElastiCache) - elasticbeanstalk (Elastic BeanStalk) - elasticloadbalancing (Elastic Load Balancing) - elasticmapreduce (Elastic MapReduce) - iam (Identity and Access Management) - importexport (Import/Export) - monitoring (CloudWatch) - rds (Relational Database Service) - simpledb (SimpleDB) - sns (Simple Notification Service) - sqs (Simple Queue Service)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L371-L540
[ "def get_location(opts=None, provider=None):\n '''\n Return the region to use, in this order:\n opts['location']\n provider['location']\n get_region_from_metadata()\n DEFAULT_LOCATION\n '''\n if opts is None:\n opts = {}\n ret = opts.get('location')\n if ret is None and provider is not None:\n ret = provider.get('location')\n if ret is None:\n ret = get_region_from_metadata()\n if ret is None:\n ret = DEFAULT_LOCATION\n return ret\n", "def sleep_exponential_backoff(attempts):\n \"\"\"\n backoff an exponential amount of time to throttle requests\n during \"API Rate Exceeded\" failures as suggested by the AWS documentation here:\n https://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html\n and also here:\n https://docs.aws.amazon.com/general/latest/gr/api-retries.html\n Failure to implement this approach results in a failure rate of >30% when using salt-cloud with\n \"--parallel\" when creating 50 or more instances with a fixed delay of 2 seconds.\n A failure rate of >10% is observed when using the salt-api with an asynchronous client\n specified (runner_async).\n \"\"\"\n time.sleep(random.uniform(1, 2**attempts))\n", "def sig2(method, endpoint, params, provider, aws_api_version):\n '''\n Sign a query against AWS services using Signature Version 2 Signing\n Process. This is documented at:\n\n http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html\n '''\n timenow = datetime.utcnow()\n timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ')\n\n # Retrieve access credentials from meta-data, or use provided\n access_key_id, secret_access_key, token = creds(provider)\n\n params_with_headers = params.copy()\n params_with_headers['AWSAccessKeyId'] = access_key_id\n params_with_headers['SignatureVersion'] = '2'\n params_with_headers['SignatureMethod'] = 'HmacSHA256'\n params_with_headers['Timestamp'] = '{0}'.format(timestamp)\n params_with_headers['Version'] = aws_api_version\n keys = sorted(params_with_headers.keys())\n values = list(list(map(params_with_headers.get, keys)))\n querystring = urlencode(list(zip(keys, values)))\n\n canonical = '{0}\\n{1}\\n/\\n{2}'.format(\n method.encode('utf-8'),\n endpoint.encode('utf-8'),\n querystring.encode('utf-8'),\n )\n\n hashed = hmac.new(secret_access_key, canonical, hashlib.sha256)\n sig = binascii.b2a_base64(hashed.digest())\n params_with_headers['Signature'] = sig.strip()\n\n # Add in security token if we have one\n if token != '':\n params_with_headers['SecurityToken'] = token\n\n return params_with_headers\n", "def sig4(method, endpoint, params, prov_dict,\n aws_api_version=DEFAULT_AWS_API_VERSION, location=None,\n product='ec2', uri='/', requesturl=None, data='', headers=None,\n role_arn=None, payload_hash=None):\n '''\n Sign a query against AWS services using Signature Version 4 Signing\n Process. This is documented at:\n\n http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html\n http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html\n http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n '''\n timenow = datetime.utcnow()\n\n # Retrieve access credentials from meta-data, or use provided\n if role_arn is None:\n access_key_id, secret_access_key, token = creds(prov_dict)\n else:\n access_key_id, secret_access_key, token = assumed_creds(prov_dict, role_arn, location=location)\n\n if location is None:\n location = get_region_from_metadata()\n if location is None:\n location = DEFAULT_LOCATION\n\n params_with_headers = params.copy()\n if product not in ('s3', 'ssm'):\n params_with_headers['Version'] = aws_api_version\n keys = sorted(params_with_headers.keys())\n values = list(map(params_with_headers.get, keys))\n querystring = urlencode(list(zip(keys, values))).replace('+', '%20')\n\n amzdate = timenow.strftime('%Y%m%dT%H%M%SZ')\n datestamp = timenow.strftime('%Y%m%d')\n new_headers = {}\n if isinstance(headers, dict):\n new_headers = headers.copy()\n\n # Create payload hash (hash of the request body content). For GET\n # requests, the payload is an empty string ('').\n if not payload_hash:\n payload_hash = salt.utils.hashutils.sha256_digest(data)\n\n new_headers['X-Amz-date'] = amzdate\n new_headers['host'] = endpoint\n new_headers['x-amz-content-sha256'] = payload_hash\n a_canonical_headers = []\n a_signed_headers = []\n\n if token != '':\n new_headers['X-Amz-security-token'] = token\n\n for header in sorted(new_headers.keys(), key=six.text_type.lower):\n lower_header = header.lower()\n a_canonical_headers.append('{0}:{1}'.format(lower_header, new_headers[header].strip()))\n a_signed_headers.append(lower_header)\n canonical_headers = '\\n'.join(a_canonical_headers) + '\\n'\n signed_headers = ';'.join(a_signed_headers)\n\n algorithm = 'AWS4-HMAC-SHA256'\n\n # Combine elements to create create canonical request\n canonical_request = '\\n'.join((\n method,\n uri,\n querystring,\n canonical_headers,\n signed_headers,\n payload_hash\n ))\n\n # Create the string to sign\n credential_scope = '/'.join((datestamp, location, product, 'aws4_request'))\n string_to_sign = '\\n'.join((\n algorithm,\n amzdate,\n credential_scope,\n salt.utils.hashutils.sha256_digest(canonical_request)\n ))\n\n # Create the signing key using the function defined above.\n signing_key = _sig_key(\n secret_access_key,\n datestamp,\n location,\n product\n )\n\n # Sign the string_to_sign using the signing_key\n signature = hmac.new(\n signing_key,\n string_to_sign.encode('utf-8'),\n hashlib.sha256).hexdigest()\n\n # Add signing information to the request\n authorization_header = (\n '{0} Credential={1}/{2}, SignedHeaders={3}, Signature={4}'\n ).format(\n algorithm,\n access_key_id,\n credential_scope,\n signed_headers,\n signature,\n )\n\n new_headers['Authorization'] = authorization_header\n\n requesturl = '{0}?{1}'.format(requesturl, querystring)\n return new_headers, requesturl\n", "def to_dict(xmltree, attr=False):\n '''\n Convert an XML tree into a dict. The tree that is passed in must be an\n ElementTree object.\n Args:\n xmltree: An ElementTree object.\n attr: If true, attributes will be parsed. If false, they will be ignored.\n\n '''\n if attr:\n return _to_full_dict(xmltree)\n else:\n return _to_dict(xmltree)\n" ]
# -*- coding: utf-8 -*- ''' Connection library for AWS .. versionadded:: 2015.5.0 This is a base library used by a number of AWS services. :depends: requests ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import sys import time import binascii from datetime import datetime import hashlib import hmac import logging import salt.config import re import random from salt.ext import six # Import Salt libs import salt.utils.hashutils import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET # Import 3rd-party libs try: import requests HAS_REQUESTS = True # pylint: disable=W0612 except ImportError: HAS_REQUESTS = False # pylint: disable=W0612 # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, zip from salt.ext.six.moves.urllib.parse import urlencode, urlparse # pylint: enable=import-error,redefined-builtin,no-name-in-module log = logging.getLogger(__name__) DEFAULT_LOCATION = 'us-east-1' DEFAULT_AWS_API_VERSION = '2014-10-01' AWS_RETRY_CODES = [ 'RequestLimitExceeded', 'InsufficientInstanceCapacity', 'InternalError', 'Unavailable', 'InsufficientAddressCapacity', 'InsufficientReservedInstanceCapacity', ] AWS_METADATA_TIMEOUT = 3.05 AWS_MAX_RETRIES = 7 IROLE_CODE = 'use-instance-role-credentials' __AccessKeyId__ = '' __SecretAccessKey__ = '' __Token__ = '' __Expiration__ = '' __Location__ = '' __AssumeCache__ = {} def sleep_exponential_backoff(attempts): """ backoff an exponential amount of time to throttle requests during "API Rate Exceeded" failures as suggested by the AWS documentation here: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html and also here: https://docs.aws.amazon.com/general/latest/gr/api-retries.html Failure to implement this approach results in a failure rate of >30% when using salt-cloud with "--parallel" when creating 50 or more instances with a fixed delay of 2 seconds. A failure rate of >10% is observed when using the salt-api with an asynchronous client specified (runner_async). """ time.sleep(random.uniform(1, 2**attempts)) def creds(provider): ''' Return the credentials for AWS signing. This could be just the id and key specified in the provider configuration, or if the id or key is set to the literal string 'use-instance-role-credentials' creds will pull the instance role credentials from the meta data, cache them, and provide them instead. ''' # Declare globals global __AccessKeyId__, __SecretAccessKey__, __Token__, __Expiration__ ret_credentials = () # if id or key is 'use-instance-role-credentials', pull them from meta-data ## if needed if provider['id'] == IROLE_CODE or provider['key'] == IROLE_CODE: # Check to see if we have cache credentials that are still good if __Expiration__ != '': timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp < __Expiration__: # Current timestamp less than expiration fo cached credentials return __AccessKeyId__, __SecretAccessKey__, __Token__ # We don't have any cached credentials, or they are expired, get them # Connections to instance meta-data must fail fast and never be proxied try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() role = result.text except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/{0}".format(role), proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' data = result.json() __AccessKeyId__ = data['AccessKeyId'] __SecretAccessKey__ = data['SecretAccessKey'] __Token__ = data['Token'] __Expiration__ = data['Expiration'] ret_credentials = __AccessKeyId__, __SecretAccessKey__, __Token__ else: ret_credentials = provider['id'], provider['key'], '' if provider.get('role_arn') is not None: provider_shadow = provider.copy() provider_shadow.pop("role_arn", None) log.info("Assuming the role: %s", provider.get('role_arn')) ret_credentials = assumed_creds(provider_shadow, role_arn=provider.get('role_arn'), location='us-east-1') return ret_credentials def sig2(method, endpoint, params, provider, aws_api_version): ''' Sign a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html ''' timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') # Retrieve access credentials from meta-data, or use provided access_key_id, secret_access_key, token = creds(provider) params_with_headers = params.copy() params_with_headers['AWSAccessKeyId'] = access_key_id params_with_headers['SignatureVersion'] = '2' params_with_headers['SignatureMethod'] = 'HmacSHA256' params_with_headers['Timestamp'] = '{0}'.format(timestamp) params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(list(map(params_with_headers.get, keys))) querystring = urlencode(list(zip(keys, values))) canonical = '{0}\n{1}\n/\n{2}'.format( method.encode('utf-8'), endpoint.encode('utf-8'), querystring.encode('utf-8'), ) hashed = hmac.new(secret_access_key, canonical, hashlib.sha256) sig = binascii.b2a_base64(hashed.digest()) params_with_headers['Signature'] = sig.strip() # Add in security token if we have one if token != '': params_with_headers['SecurityToken'] = token return params_with_headers def assumed_creds(prov_dict, role_arn, location=None): valid_session_name_re = re.compile("[^a-z0-9A-Z+=,.@-]") # current time in epoch seconds now = time.mktime(datetime.utcnow().timetuple()) for key, creds in __AssumeCache__.items(): if (creds["Expiration"] - now) <= 120: __AssumeCache__.delete(key) if role_arn in __AssumeCache__: c = __AssumeCache__[role_arn] return c["AccessKeyId"], c["SecretAccessKey"], c["SessionToken"] version = "2011-06-15" session_name = valid_session_name_re.sub('', salt.config.get_id({"root_dir": None})[0])[0:63] headers, requesturl = sig4( 'GET', 'sts.amazonaws.com', params={ "Version": version, "Action": "AssumeRole", "RoleSessionName": session_name, "RoleArn": role_arn, "Policy": '{"Version":"2012-10-17","Statement":[{"Sid":"Stmt1", "Effect":"Allow","Action":"*","Resource":"*"}]}', "DurationSeconds": "3600" }, aws_api_version=version, data='', uri='/', prov_dict=prov_dict, product='sts', location=location, requesturl="https://sts.amazonaws.com/" ) headers["Accept"] = "application/json" result = requests.request('GET', requesturl, headers=headers, data='', verify=True) if result.status_code >= 400: log.info('AssumeRole response: %s', result.content) result.raise_for_status() resp = result.json() data = resp["AssumeRoleResponse"]["AssumeRoleResult"]["Credentials"] __AssumeCache__[role_arn] = data return data["AccessKeyId"], data["SecretAccessKey"], data["SessionToken"] def sig4(method, endpoint, params, prov_dict, aws_api_version=DEFAULT_AWS_API_VERSION, location=None, product='ec2', uri='/', requesturl=None, data='', headers=None, role_arn=None, payload_hash=None): ''' Sign a query against AWS services using Signature Version 4 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html ''' timenow = datetime.utcnow() # Retrieve access credentials from meta-data, or use provided if role_arn is None: access_key_id, secret_access_key, token = creds(prov_dict) else: access_key_id, secret_access_key, token = assumed_creds(prov_dict, role_arn, location=location) if location is None: location = get_region_from_metadata() if location is None: location = DEFAULT_LOCATION params_with_headers = params.copy() if product not in ('s3', 'ssm'): params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(map(params_with_headers.get, keys)) querystring = urlencode(list(zip(keys, values))).replace('+', '%20') amzdate = timenow.strftime('%Y%m%dT%H%M%SZ') datestamp = timenow.strftime('%Y%m%d') new_headers = {} if isinstance(headers, dict): new_headers = headers.copy() # Create payload hash (hash of the request body content). For GET # requests, the payload is an empty string (''). if not payload_hash: payload_hash = salt.utils.hashutils.sha256_digest(data) new_headers['X-Amz-date'] = amzdate new_headers['host'] = endpoint new_headers['x-amz-content-sha256'] = payload_hash a_canonical_headers = [] a_signed_headers = [] if token != '': new_headers['X-Amz-security-token'] = token for header in sorted(new_headers.keys(), key=six.text_type.lower): lower_header = header.lower() a_canonical_headers.append('{0}:{1}'.format(lower_header, new_headers[header].strip())) a_signed_headers.append(lower_header) canonical_headers = '\n'.join(a_canonical_headers) + '\n' signed_headers = ';'.join(a_signed_headers) algorithm = 'AWS4-HMAC-SHA256' # Combine elements to create create canonical request canonical_request = '\n'.join(( method, uri, querystring, canonical_headers, signed_headers, payload_hash )) # Create the string to sign credential_scope = '/'.join((datestamp, location, product, 'aws4_request')) string_to_sign = '\n'.join(( algorithm, amzdate, credential_scope, salt.utils.hashutils.sha256_digest(canonical_request) )) # Create the signing key using the function defined above. signing_key = _sig_key( secret_access_key, datestamp, location, product ) # Sign the string_to_sign using the signing_key signature = hmac.new( signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest() # Add signing information to the request authorization_header = ( '{0} Credential={1}/{2}, SignedHeaders={3}, Signature={4}' ).format( algorithm, access_key_id, credential_scope, signed_headers, signature, ) new_headers['Authorization'] = authorization_header requesturl = '{0}?{1}'.format(requesturl, querystring) return new_headers, requesturl def _sign(key, msg): ''' Key derivation functions. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() def _sig_key(key, date_stamp, regionName, serviceName): ''' Get a signature key. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp) if regionName: kRegion = _sign(kDate, regionName) kService = _sign(kRegion, serviceName) else: kService = _sign(kDate, serviceName) kSigning = _sign(kService, 'aws4_request') return kSigning def get_region_from_metadata(): ''' Try to get region from instance identity document and cache it .. versionadded:: 2015.5.6 ''' global __Location__ if __Location__ == 'do-not-get-from-metadata': log.debug('Previously failed to get AWS region from metadata. Not trying again.') return None # Cached region if __Location__ != '': return __Location__ try: # Connections to instance meta-data must fail fast and never be proxied result = requests.get( "http://169.254.169.254/latest/dynamic/instance-identity/document", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) except requests.exceptions.RequestException: log.warning('Failed to get AWS region from instance metadata.', exc_info=True) # Do not try again __Location__ = 'do-not-get-from-metadata' return None try: region = result.json()['region'] __Location__ = region return __Location__ except (ValueError, KeyError): log.warning('Failed to decode JSON from instance metadata.') return None return None def get_location(opts=None, provider=None): ''' Return the region to use, in this order: opts['location'] provider['location'] get_region_from_metadata() DEFAULT_LOCATION ''' if opts is None: opts = {} ret = opts.get('location') if ret is None and provider is not None: ret = provider.get('location') if ret is None: ret = get_region_from_metadata() if ret is None: ret = DEFAULT_LOCATION return ret
saltstack/salt
salt/utils/aws.py
get_region_from_metadata
python
def get_region_from_metadata(): ''' Try to get region from instance identity document and cache it .. versionadded:: 2015.5.6 ''' global __Location__ if __Location__ == 'do-not-get-from-metadata': log.debug('Previously failed to get AWS region from metadata. Not trying again.') return None # Cached region if __Location__ != '': return __Location__ try: # Connections to instance meta-data must fail fast and never be proxied result = requests.get( "http://169.254.169.254/latest/dynamic/instance-identity/document", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) except requests.exceptions.RequestException: log.warning('Failed to get AWS region from instance metadata.', exc_info=True) # Do not try again __Location__ = 'do-not-get-from-metadata' return None try: region = result.json()['region'] __Location__ = region return __Location__ except (ValueError, KeyError): log.warning('Failed to decode JSON from instance metadata.') return None return None
Try to get region from instance identity document and cache it .. versionadded:: 2015.5.6
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L543-L579
null
# -*- coding: utf-8 -*- ''' Connection library for AWS .. versionadded:: 2015.5.0 This is a base library used by a number of AWS services. :depends: requests ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import sys import time import binascii from datetime import datetime import hashlib import hmac import logging import salt.config import re import random from salt.ext import six # Import Salt libs import salt.utils.hashutils import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET # Import 3rd-party libs try: import requests HAS_REQUESTS = True # pylint: disable=W0612 except ImportError: HAS_REQUESTS = False # pylint: disable=W0612 # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, zip from salt.ext.six.moves.urllib.parse import urlencode, urlparse # pylint: enable=import-error,redefined-builtin,no-name-in-module log = logging.getLogger(__name__) DEFAULT_LOCATION = 'us-east-1' DEFAULT_AWS_API_VERSION = '2014-10-01' AWS_RETRY_CODES = [ 'RequestLimitExceeded', 'InsufficientInstanceCapacity', 'InternalError', 'Unavailable', 'InsufficientAddressCapacity', 'InsufficientReservedInstanceCapacity', ] AWS_METADATA_TIMEOUT = 3.05 AWS_MAX_RETRIES = 7 IROLE_CODE = 'use-instance-role-credentials' __AccessKeyId__ = '' __SecretAccessKey__ = '' __Token__ = '' __Expiration__ = '' __Location__ = '' __AssumeCache__ = {} def sleep_exponential_backoff(attempts): """ backoff an exponential amount of time to throttle requests during "API Rate Exceeded" failures as suggested by the AWS documentation here: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html and also here: https://docs.aws.amazon.com/general/latest/gr/api-retries.html Failure to implement this approach results in a failure rate of >30% when using salt-cloud with "--parallel" when creating 50 or more instances with a fixed delay of 2 seconds. A failure rate of >10% is observed when using the salt-api with an asynchronous client specified (runner_async). """ time.sleep(random.uniform(1, 2**attempts)) def creds(provider): ''' Return the credentials for AWS signing. This could be just the id and key specified in the provider configuration, or if the id or key is set to the literal string 'use-instance-role-credentials' creds will pull the instance role credentials from the meta data, cache them, and provide them instead. ''' # Declare globals global __AccessKeyId__, __SecretAccessKey__, __Token__, __Expiration__ ret_credentials = () # if id or key is 'use-instance-role-credentials', pull them from meta-data ## if needed if provider['id'] == IROLE_CODE or provider['key'] == IROLE_CODE: # Check to see if we have cache credentials that are still good if __Expiration__ != '': timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp < __Expiration__: # Current timestamp less than expiration fo cached credentials return __AccessKeyId__, __SecretAccessKey__, __Token__ # We don't have any cached credentials, or they are expired, get them # Connections to instance meta-data must fail fast and never be proxied try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() role = result.text except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/{0}".format(role), proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' data = result.json() __AccessKeyId__ = data['AccessKeyId'] __SecretAccessKey__ = data['SecretAccessKey'] __Token__ = data['Token'] __Expiration__ = data['Expiration'] ret_credentials = __AccessKeyId__, __SecretAccessKey__, __Token__ else: ret_credentials = provider['id'], provider['key'], '' if provider.get('role_arn') is not None: provider_shadow = provider.copy() provider_shadow.pop("role_arn", None) log.info("Assuming the role: %s", provider.get('role_arn')) ret_credentials = assumed_creds(provider_shadow, role_arn=provider.get('role_arn'), location='us-east-1') return ret_credentials def sig2(method, endpoint, params, provider, aws_api_version): ''' Sign a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html ''' timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') # Retrieve access credentials from meta-data, or use provided access_key_id, secret_access_key, token = creds(provider) params_with_headers = params.copy() params_with_headers['AWSAccessKeyId'] = access_key_id params_with_headers['SignatureVersion'] = '2' params_with_headers['SignatureMethod'] = 'HmacSHA256' params_with_headers['Timestamp'] = '{0}'.format(timestamp) params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(list(map(params_with_headers.get, keys))) querystring = urlencode(list(zip(keys, values))) canonical = '{0}\n{1}\n/\n{2}'.format( method.encode('utf-8'), endpoint.encode('utf-8'), querystring.encode('utf-8'), ) hashed = hmac.new(secret_access_key, canonical, hashlib.sha256) sig = binascii.b2a_base64(hashed.digest()) params_with_headers['Signature'] = sig.strip() # Add in security token if we have one if token != '': params_with_headers['SecurityToken'] = token return params_with_headers def assumed_creds(prov_dict, role_arn, location=None): valid_session_name_re = re.compile("[^a-z0-9A-Z+=,.@-]") # current time in epoch seconds now = time.mktime(datetime.utcnow().timetuple()) for key, creds in __AssumeCache__.items(): if (creds["Expiration"] - now) <= 120: __AssumeCache__.delete(key) if role_arn in __AssumeCache__: c = __AssumeCache__[role_arn] return c["AccessKeyId"], c["SecretAccessKey"], c["SessionToken"] version = "2011-06-15" session_name = valid_session_name_re.sub('', salt.config.get_id({"root_dir": None})[0])[0:63] headers, requesturl = sig4( 'GET', 'sts.amazonaws.com', params={ "Version": version, "Action": "AssumeRole", "RoleSessionName": session_name, "RoleArn": role_arn, "Policy": '{"Version":"2012-10-17","Statement":[{"Sid":"Stmt1", "Effect":"Allow","Action":"*","Resource":"*"}]}', "DurationSeconds": "3600" }, aws_api_version=version, data='', uri='/', prov_dict=prov_dict, product='sts', location=location, requesturl="https://sts.amazonaws.com/" ) headers["Accept"] = "application/json" result = requests.request('GET', requesturl, headers=headers, data='', verify=True) if result.status_code >= 400: log.info('AssumeRole response: %s', result.content) result.raise_for_status() resp = result.json() data = resp["AssumeRoleResponse"]["AssumeRoleResult"]["Credentials"] __AssumeCache__[role_arn] = data return data["AccessKeyId"], data["SecretAccessKey"], data["SessionToken"] def sig4(method, endpoint, params, prov_dict, aws_api_version=DEFAULT_AWS_API_VERSION, location=None, product='ec2', uri='/', requesturl=None, data='', headers=None, role_arn=None, payload_hash=None): ''' Sign a query against AWS services using Signature Version 4 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html ''' timenow = datetime.utcnow() # Retrieve access credentials from meta-data, or use provided if role_arn is None: access_key_id, secret_access_key, token = creds(prov_dict) else: access_key_id, secret_access_key, token = assumed_creds(prov_dict, role_arn, location=location) if location is None: location = get_region_from_metadata() if location is None: location = DEFAULT_LOCATION params_with_headers = params.copy() if product not in ('s3', 'ssm'): params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(map(params_with_headers.get, keys)) querystring = urlencode(list(zip(keys, values))).replace('+', '%20') amzdate = timenow.strftime('%Y%m%dT%H%M%SZ') datestamp = timenow.strftime('%Y%m%d') new_headers = {} if isinstance(headers, dict): new_headers = headers.copy() # Create payload hash (hash of the request body content). For GET # requests, the payload is an empty string (''). if not payload_hash: payload_hash = salt.utils.hashutils.sha256_digest(data) new_headers['X-Amz-date'] = amzdate new_headers['host'] = endpoint new_headers['x-amz-content-sha256'] = payload_hash a_canonical_headers = [] a_signed_headers = [] if token != '': new_headers['X-Amz-security-token'] = token for header in sorted(new_headers.keys(), key=six.text_type.lower): lower_header = header.lower() a_canonical_headers.append('{0}:{1}'.format(lower_header, new_headers[header].strip())) a_signed_headers.append(lower_header) canonical_headers = '\n'.join(a_canonical_headers) + '\n' signed_headers = ';'.join(a_signed_headers) algorithm = 'AWS4-HMAC-SHA256' # Combine elements to create create canonical request canonical_request = '\n'.join(( method, uri, querystring, canonical_headers, signed_headers, payload_hash )) # Create the string to sign credential_scope = '/'.join((datestamp, location, product, 'aws4_request')) string_to_sign = '\n'.join(( algorithm, amzdate, credential_scope, salt.utils.hashutils.sha256_digest(canonical_request) )) # Create the signing key using the function defined above. signing_key = _sig_key( secret_access_key, datestamp, location, product ) # Sign the string_to_sign using the signing_key signature = hmac.new( signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest() # Add signing information to the request authorization_header = ( '{0} Credential={1}/{2}, SignedHeaders={3}, Signature={4}' ).format( algorithm, access_key_id, credential_scope, signed_headers, signature, ) new_headers['Authorization'] = authorization_header requesturl = '{0}?{1}'.format(requesturl, querystring) return new_headers, requesturl def _sign(key, msg): ''' Key derivation functions. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() def _sig_key(key, date_stamp, regionName, serviceName): ''' Get a signature key. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp) if regionName: kRegion = _sign(kDate, regionName) kService = _sign(kRegion, serviceName) else: kService = _sign(kDate, serviceName) kSigning = _sign(kService, 'aws4_request') return kSigning def query(params=None, setname=None, requesturl=None, location=None, return_url=False, return_root=False, opts=None, provider=None, endpoint=None, product='ec2', sigver='2'): ''' Perform a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html Regions and endpoints are documented at: http://docs.aws.amazon.com/general/latest/gr/rande.html Default ``product`` is ``ec2``. Valid ``product`` names are: .. code-block: yaml - autoscaling (Auto Scaling) - cloudformation (CloudFormation) - ec2 (Elastic Compute Cloud) - elasticache (ElastiCache) - elasticbeanstalk (Elastic BeanStalk) - elasticloadbalancing (Elastic Load Balancing) - elasticmapreduce (Elastic MapReduce) - iam (Identity and Access Management) - importexport (Import/Export) - monitoring (CloudWatch) - rds (Relational Database Service) - simpledb (SimpleDB) - sns (Simple Notification Service) - sqs (Simple Queue Service) ''' if params is None: params = {} if opts is None: opts = {} function = opts.get('function', (None, product)) providers = opts.get('providers', {}) if provider is None: prov_dict = providers.get(function[1], {}).get(product, {}) if prov_dict: driver = list(list(prov_dict.keys()))[0] provider = providers.get(driver, product) else: prov_dict = providers.get(provider, {}).get(product, {}) service_url = prov_dict.get('service_url', 'amazonaws.com') if not location: location = get_location(opts, prov_dict) if endpoint is None: if not requesturl: endpoint = prov_dict.get( 'endpoint', '{0}.{1}.{2}'.format(product, location, service_url) ) requesturl = 'https://{0}/'.format(endpoint) else: endpoint = urlparse(requesturl).netloc if endpoint == '': endpoint_err = ('Could not find a valid endpoint in the ' 'requesturl: {0}. Looking for something ' 'like https://some.aws.endpoint/?args').format( requesturl ) log.error(endpoint_err) if return_url is True: return {'error': endpoint_err}, requesturl return {'error': endpoint_err} log.debug('Using AWS endpoint: %s', endpoint) method = 'GET' aws_api_version = prov_dict.get( 'aws_api_version', prov_dict.get( '{0}_api_version'.format(product), DEFAULT_AWS_API_VERSION ) ) # Fallback to ec2's id & key if none is found, for this component if not prov_dict.get('id', None): prov_dict['id'] = providers.get(provider, {}).get('ec2', {}).get('id', {}) prov_dict['key'] = providers.get(provider, {}).get('ec2', {}).get('key', {}) if sigver == '4': headers, requesturl = sig4( method, endpoint, params, prov_dict, aws_api_version, location, product, requesturl=requesturl ) params_with_headers = {} else: params_with_headers = sig2( method, endpoint, params, prov_dict, aws_api_version ) headers = {} attempts = 0 while attempts < AWS_MAX_RETRIES: log.debug('AWS Request: %s', requesturl) log.trace('AWS Request Parameters: %s', params_with_headers) try: result = requests.get(requesturl, headers=headers, params=params_with_headers) log.debug('AWS Response Status Code: %s', result.status_code) log.trace( 'AWS Response Text: %s', result.text ) result.raise_for_status() break except requests.exceptions.HTTPError as exc: root = ET.fromstring(exc.response.content) data = xml.to_dict(root) # check to see if we should retry the query err_code = data.get('Errors', {}).get('Error', {}).get('Code', '') if attempts < AWS_MAX_RETRIES and err_code and err_code in AWS_RETRY_CODES: attempts += 1 log.error( 'AWS Response Status Code and Error: [%s %s] %s; ' 'Attempts remaining: %s', exc.response.status_code, exc, data, attempts ) sleep_exponential_backoff(attempts) continue log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} else: log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} root = ET.fromstring(result.text) items = root[1] if return_root is True: items = root if setname: if sys.version_info < (2, 7): children_len = len(root.getchildren()) else: children_len = len(root) for item in range(0, children_len): comps = root[item].tag.split('}') if comps[1] == setname: items = root[item] ret = [] for item in items: ret.append(xml.to_dict(item)) if return_url is True: return ret, requesturl return ret def get_location(opts=None, provider=None): ''' Return the region to use, in this order: opts['location'] provider['location'] get_region_from_metadata() DEFAULT_LOCATION ''' if opts is None: opts = {} ret = opts.get('location') if ret is None and provider is not None: ret = provider.get('location') if ret is None: ret = get_region_from_metadata() if ret is None: ret = DEFAULT_LOCATION return ret
saltstack/salt
salt/utils/aws.py
get_location
python
def get_location(opts=None, provider=None): ''' Return the region to use, in this order: opts['location'] provider['location'] get_region_from_metadata() DEFAULT_LOCATION ''' if opts is None: opts = {} ret = opts.get('location') if ret is None and provider is not None: ret = provider.get('location') if ret is None: ret = get_region_from_metadata() if ret is None: ret = DEFAULT_LOCATION return ret
Return the region to use, in this order: opts['location'] provider['location'] get_region_from_metadata() DEFAULT_LOCATION
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L582-L599
[ "def get_region_from_metadata():\n '''\n Try to get region from instance identity document and cache it\n\n .. versionadded:: 2015.5.6\n '''\n global __Location__\n\n if __Location__ == 'do-not-get-from-metadata':\n log.debug('Previously failed to get AWS region from metadata. Not trying again.')\n return None\n\n # Cached region\n if __Location__ != '':\n return __Location__\n\n try:\n # Connections to instance meta-data must fail fast and never be proxied\n result = requests.get(\n \"http://169.254.169.254/latest/dynamic/instance-identity/document\",\n proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT,\n )\n except requests.exceptions.RequestException:\n log.warning('Failed to get AWS region from instance metadata.', exc_info=True)\n # Do not try again\n __Location__ = 'do-not-get-from-metadata'\n return None\n\n try:\n region = result.json()['region']\n __Location__ = region\n return __Location__\n except (ValueError, KeyError):\n log.warning('Failed to decode JSON from instance metadata.')\n return None\n\n return None\n" ]
# -*- coding: utf-8 -*- ''' Connection library for AWS .. versionadded:: 2015.5.0 This is a base library used by a number of AWS services. :depends: requests ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import sys import time import binascii from datetime import datetime import hashlib import hmac import logging import salt.config import re import random from salt.ext import six # Import Salt libs import salt.utils.hashutils import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET # Import 3rd-party libs try: import requests HAS_REQUESTS = True # pylint: disable=W0612 except ImportError: HAS_REQUESTS = False # pylint: disable=W0612 # pylint: disable=import-error,redefined-builtin,no-name-in-module from salt.ext.six.moves import map, range, zip from salt.ext.six.moves.urllib.parse import urlencode, urlparse # pylint: enable=import-error,redefined-builtin,no-name-in-module log = logging.getLogger(__name__) DEFAULT_LOCATION = 'us-east-1' DEFAULT_AWS_API_VERSION = '2014-10-01' AWS_RETRY_CODES = [ 'RequestLimitExceeded', 'InsufficientInstanceCapacity', 'InternalError', 'Unavailable', 'InsufficientAddressCapacity', 'InsufficientReservedInstanceCapacity', ] AWS_METADATA_TIMEOUT = 3.05 AWS_MAX_RETRIES = 7 IROLE_CODE = 'use-instance-role-credentials' __AccessKeyId__ = '' __SecretAccessKey__ = '' __Token__ = '' __Expiration__ = '' __Location__ = '' __AssumeCache__ = {} def sleep_exponential_backoff(attempts): """ backoff an exponential amount of time to throttle requests during "API Rate Exceeded" failures as suggested by the AWS documentation here: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html and also here: https://docs.aws.amazon.com/general/latest/gr/api-retries.html Failure to implement this approach results in a failure rate of >30% when using salt-cloud with "--parallel" when creating 50 or more instances with a fixed delay of 2 seconds. A failure rate of >10% is observed when using the salt-api with an asynchronous client specified (runner_async). """ time.sleep(random.uniform(1, 2**attempts)) def creds(provider): ''' Return the credentials for AWS signing. This could be just the id and key specified in the provider configuration, or if the id or key is set to the literal string 'use-instance-role-credentials' creds will pull the instance role credentials from the meta data, cache them, and provide them instead. ''' # Declare globals global __AccessKeyId__, __SecretAccessKey__, __Token__, __Expiration__ ret_credentials = () # if id or key is 'use-instance-role-credentials', pull them from meta-data ## if needed if provider['id'] == IROLE_CODE or provider['key'] == IROLE_CODE: # Check to see if we have cache credentials that are still good if __Expiration__ != '': timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp < __Expiration__: # Current timestamp less than expiration fo cached credentials return __AccessKeyId__, __SecretAccessKey__, __Token__ # We don't have any cached credentials, or they are expired, get them # Connections to instance meta-data must fail fast and never be proxied try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() role = result.text except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/{0}".format(role), proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' data = result.json() __AccessKeyId__ = data['AccessKeyId'] __SecretAccessKey__ = data['SecretAccessKey'] __Token__ = data['Token'] __Expiration__ = data['Expiration'] ret_credentials = __AccessKeyId__, __SecretAccessKey__, __Token__ else: ret_credentials = provider['id'], provider['key'], '' if provider.get('role_arn') is not None: provider_shadow = provider.copy() provider_shadow.pop("role_arn", None) log.info("Assuming the role: %s", provider.get('role_arn')) ret_credentials = assumed_creds(provider_shadow, role_arn=provider.get('role_arn'), location='us-east-1') return ret_credentials def sig2(method, endpoint, params, provider, aws_api_version): ''' Sign a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html ''' timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') # Retrieve access credentials from meta-data, or use provided access_key_id, secret_access_key, token = creds(provider) params_with_headers = params.copy() params_with_headers['AWSAccessKeyId'] = access_key_id params_with_headers['SignatureVersion'] = '2' params_with_headers['SignatureMethod'] = 'HmacSHA256' params_with_headers['Timestamp'] = '{0}'.format(timestamp) params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(list(map(params_with_headers.get, keys))) querystring = urlencode(list(zip(keys, values))) canonical = '{0}\n{1}\n/\n{2}'.format( method.encode('utf-8'), endpoint.encode('utf-8'), querystring.encode('utf-8'), ) hashed = hmac.new(secret_access_key, canonical, hashlib.sha256) sig = binascii.b2a_base64(hashed.digest()) params_with_headers['Signature'] = sig.strip() # Add in security token if we have one if token != '': params_with_headers['SecurityToken'] = token return params_with_headers def assumed_creds(prov_dict, role_arn, location=None): valid_session_name_re = re.compile("[^a-z0-9A-Z+=,.@-]") # current time in epoch seconds now = time.mktime(datetime.utcnow().timetuple()) for key, creds in __AssumeCache__.items(): if (creds["Expiration"] - now) <= 120: __AssumeCache__.delete(key) if role_arn in __AssumeCache__: c = __AssumeCache__[role_arn] return c["AccessKeyId"], c["SecretAccessKey"], c["SessionToken"] version = "2011-06-15" session_name = valid_session_name_re.sub('', salt.config.get_id({"root_dir": None})[0])[0:63] headers, requesturl = sig4( 'GET', 'sts.amazonaws.com', params={ "Version": version, "Action": "AssumeRole", "RoleSessionName": session_name, "RoleArn": role_arn, "Policy": '{"Version":"2012-10-17","Statement":[{"Sid":"Stmt1", "Effect":"Allow","Action":"*","Resource":"*"}]}', "DurationSeconds": "3600" }, aws_api_version=version, data='', uri='/', prov_dict=prov_dict, product='sts', location=location, requesturl="https://sts.amazonaws.com/" ) headers["Accept"] = "application/json" result = requests.request('GET', requesturl, headers=headers, data='', verify=True) if result.status_code >= 400: log.info('AssumeRole response: %s', result.content) result.raise_for_status() resp = result.json() data = resp["AssumeRoleResponse"]["AssumeRoleResult"]["Credentials"] __AssumeCache__[role_arn] = data return data["AccessKeyId"], data["SecretAccessKey"], data["SessionToken"] def sig4(method, endpoint, params, prov_dict, aws_api_version=DEFAULT_AWS_API_VERSION, location=None, product='ec2', uri='/', requesturl=None, data='', headers=None, role_arn=None, payload_hash=None): ''' Sign a query against AWS services using Signature Version 4 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html ''' timenow = datetime.utcnow() # Retrieve access credentials from meta-data, or use provided if role_arn is None: access_key_id, secret_access_key, token = creds(prov_dict) else: access_key_id, secret_access_key, token = assumed_creds(prov_dict, role_arn, location=location) if location is None: location = get_region_from_metadata() if location is None: location = DEFAULT_LOCATION params_with_headers = params.copy() if product not in ('s3', 'ssm'): params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(map(params_with_headers.get, keys)) querystring = urlencode(list(zip(keys, values))).replace('+', '%20') amzdate = timenow.strftime('%Y%m%dT%H%M%SZ') datestamp = timenow.strftime('%Y%m%d') new_headers = {} if isinstance(headers, dict): new_headers = headers.copy() # Create payload hash (hash of the request body content). For GET # requests, the payload is an empty string (''). if not payload_hash: payload_hash = salt.utils.hashutils.sha256_digest(data) new_headers['X-Amz-date'] = amzdate new_headers['host'] = endpoint new_headers['x-amz-content-sha256'] = payload_hash a_canonical_headers = [] a_signed_headers = [] if token != '': new_headers['X-Amz-security-token'] = token for header in sorted(new_headers.keys(), key=six.text_type.lower): lower_header = header.lower() a_canonical_headers.append('{0}:{1}'.format(lower_header, new_headers[header].strip())) a_signed_headers.append(lower_header) canonical_headers = '\n'.join(a_canonical_headers) + '\n' signed_headers = ';'.join(a_signed_headers) algorithm = 'AWS4-HMAC-SHA256' # Combine elements to create create canonical request canonical_request = '\n'.join(( method, uri, querystring, canonical_headers, signed_headers, payload_hash )) # Create the string to sign credential_scope = '/'.join((datestamp, location, product, 'aws4_request')) string_to_sign = '\n'.join(( algorithm, amzdate, credential_scope, salt.utils.hashutils.sha256_digest(canonical_request) )) # Create the signing key using the function defined above. signing_key = _sig_key( secret_access_key, datestamp, location, product ) # Sign the string_to_sign using the signing_key signature = hmac.new( signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest() # Add signing information to the request authorization_header = ( '{0} Credential={1}/{2}, SignedHeaders={3}, Signature={4}' ).format( algorithm, access_key_id, credential_scope, signed_headers, signature, ) new_headers['Authorization'] = authorization_header requesturl = '{0}?{1}'.format(requesturl, querystring) return new_headers, requesturl def _sign(key, msg): ''' Key derivation functions. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() def _sig_key(key, date_stamp, regionName, serviceName): ''' Get a signature key. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp) if regionName: kRegion = _sign(kDate, regionName) kService = _sign(kRegion, serviceName) else: kService = _sign(kDate, serviceName) kSigning = _sign(kService, 'aws4_request') return kSigning def query(params=None, setname=None, requesturl=None, location=None, return_url=False, return_root=False, opts=None, provider=None, endpoint=None, product='ec2', sigver='2'): ''' Perform a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html Regions and endpoints are documented at: http://docs.aws.amazon.com/general/latest/gr/rande.html Default ``product`` is ``ec2``. Valid ``product`` names are: .. code-block: yaml - autoscaling (Auto Scaling) - cloudformation (CloudFormation) - ec2 (Elastic Compute Cloud) - elasticache (ElastiCache) - elasticbeanstalk (Elastic BeanStalk) - elasticloadbalancing (Elastic Load Balancing) - elasticmapreduce (Elastic MapReduce) - iam (Identity and Access Management) - importexport (Import/Export) - monitoring (CloudWatch) - rds (Relational Database Service) - simpledb (SimpleDB) - sns (Simple Notification Service) - sqs (Simple Queue Service) ''' if params is None: params = {} if opts is None: opts = {} function = opts.get('function', (None, product)) providers = opts.get('providers', {}) if provider is None: prov_dict = providers.get(function[1], {}).get(product, {}) if prov_dict: driver = list(list(prov_dict.keys()))[0] provider = providers.get(driver, product) else: prov_dict = providers.get(provider, {}).get(product, {}) service_url = prov_dict.get('service_url', 'amazonaws.com') if not location: location = get_location(opts, prov_dict) if endpoint is None: if not requesturl: endpoint = prov_dict.get( 'endpoint', '{0}.{1}.{2}'.format(product, location, service_url) ) requesturl = 'https://{0}/'.format(endpoint) else: endpoint = urlparse(requesturl).netloc if endpoint == '': endpoint_err = ('Could not find a valid endpoint in the ' 'requesturl: {0}. Looking for something ' 'like https://some.aws.endpoint/?args').format( requesturl ) log.error(endpoint_err) if return_url is True: return {'error': endpoint_err}, requesturl return {'error': endpoint_err} log.debug('Using AWS endpoint: %s', endpoint) method = 'GET' aws_api_version = prov_dict.get( 'aws_api_version', prov_dict.get( '{0}_api_version'.format(product), DEFAULT_AWS_API_VERSION ) ) # Fallback to ec2's id & key if none is found, for this component if not prov_dict.get('id', None): prov_dict['id'] = providers.get(provider, {}).get('ec2', {}).get('id', {}) prov_dict['key'] = providers.get(provider, {}).get('ec2', {}).get('key', {}) if sigver == '4': headers, requesturl = sig4( method, endpoint, params, prov_dict, aws_api_version, location, product, requesturl=requesturl ) params_with_headers = {} else: params_with_headers = sig2( method, endpoint, params, prov_dict, aws_api_version ) headers = {} attempts = 0 while attempts < AWS_MAX_RETRIES: log.debug('AWS Request: %s', requesturl) log.trace('AWS Request Parameters: %s', params_with_headers) try: result = requests.get(requesturl, headers=headers, params=params_with_headers) log.debug('AWS Response Status Code: %s', result.status_code) log.trace( 'AWS Response Text: %s', result.text ) result.raise_for_status() break except requests.exceptions.HTTPError as exc: root = ET.fromstring(exc.response.content) data = xml.to_dict(root) # check to see if we should retry the query err_code = data.get('Errors', {}).get('Error', {}).get('Code', '') if attempts < AWS_MAX_RETRIES and err_code and err_code in AWS_RETRY_CODES: attempts += 1 log.error( 'AWS Response Status Code and Error: [%s %s] %s; ' 'Attempts remaining: %s', exc.response.status_code, exc, data, attempts ) sleep_exponential_backoff(attempts) continue log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} else: log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} root = ET.fromstring(result.text) items = root[1] if return_root is True: items = root if setname: if sys.version_info < (2, 7): children_len = len(root.getchildren()) else: children_len = len(root) for item in range(0, children_len): comps = root[item].tag.split('}') if comps[1] == setname: items = root[item] ret = [] for item in items: ret.append(xml.to_dict(item)) if return_url is True: return ret, requesturl return ret def get_region_from_metadata(): ''' Try to get region from instance identity document and cache it .. versionadded:: 2015.5.6 ''' global __Location__ if __Location__ == 'do-not-get-from-metadata': log.debug('Previously failed to get AWS region from metadata. Not trying again.') return None # Cached region if __Location__ != '': return __Location__ try: # Connections to instance meta-data must fail fast and never be proxied result = requests.get( "http://169.254.169.254/latest/dynamic/instance-identity/document", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) except requests.exceptions.RequestException: log.warning('Failed to get AWS region from instance metadata.', exc_info=True) # Do not try again __Location__ = 'do-not-get-from-metadata' return None try: region = result.json()['region'] __Location__ = region return __Location__ except (ValueError, KeyError): log.warning('Failed to decode JSON from instance metadata.') return None return None
saltstack/salt
salt/daemons/__init__.py
extract_masters
python
def extract_masters(opts, masters='master', port=None, raise_if_empty=True): ''' Parses opts and generates a list of master (host,port) addresses. By default looks for list of masters in opts['master'] and uses opts['master_port'] as the default port when otherwise not provided. Use the opts key given by masters for the masters list, default is 'master' If parameter port is not None then uses the default port given by port Returns a list of host address dicts of the form [ { 'external': (host,port), 'internal': (host, port) }, ... ] When only one address is provided it is assigned to the external address field When not provided the internal address field is set to None. For a given master the syntax options are as follows: hostname [port] external: hostname [port] [internal: hostaddress [port]] Where the hostname string could be either an FQDN or host address in dotted number notation. master.example.com 10.0.2.110 And the hostadress is in dotted number notation The space delimited port is optional and if not provided a default is used. The internal address is optional and if not provided is set to None Examples showing the YAML in /etc/salt/master conf file: 1) Single host name string (fqdn or dotted address) a) master: me.example.com b) master: localhost c) master: 10.0.2.205 2) Single host name string with port a) master: me.example.com 4506 b) master: 10.0.2.205 4510 3) Single master with external and optional internal host addresses for nat in a dict master: external: me.example.com 4506 internal: 10.0.2.100 4506 3) One or host host names with optional ports in a list master: - me.example.com 4506 - you.example.com 4510 - 8.8.8.8 - they.example.com 4506 - 8.8.4.4 4506 4) One or more host name with external and optional internal host addresses for Nat in a list of dicts master: - external: me.example.com 4506 internal: 10.0.2.100 4506 - external: you.example.com 4506 internal: 10.0.2.101 4506 - external: we.example.com - they.example.com ''' if port is not None: master_port = opts.get(port) else: master_port = opts.get('master_port') try: master_port = int(master_port) except ValueError: master_port = None if not master_port: emsg = "Invalid or missing opts['master_port']." log.error(emsg) raise ValueError(emsg) entries = opts.get(masters, []) if not entries: emsg = "Invalid or missing opts['{0}'].".format(masters) log.error(emsg) if raise_if_empty: raise ValueError(emsg) hostages = [] # extract candidate hostage (hostname dict) from entries if is_non_string_sequence(entries): # multiple master addresses provided for entry in entries: if isinstance(entry, Mapping): # mapping external = entry.get('external', '') internal = entry.get('internal', '') hostages.append(dict(external=external, internal=internal)) elif isinstance(entry, six.string_types): # string external = entry internal = '' hostages.append(dict(external=external, internal=internal)) elif isinstance(entries, Mapping): # mapping external = entries.get('external', '') internal = entries.get('internal', '') hostages.append(dict(external=external, internal=internal)) elif isinstance(entries, six.string_types): # string external = entries internal = '' hostages.append(dict(external=external, internal=internal)) # now parse each hostname string for host and optional port masters = [] for hostage in hostages: external = hostage['external'] internal = hostage['internal'] if external: external = parse_hostname(external, master_port) if not external: continue # must have a valid external host address internal = parse_hostname(internal, master_port) masters.append(dict(external=external, internal=internal)) return masters
Parses opts and generates a list of master (host,port) addresses. By default looks for list of masters in opts['master'] and uses opts['master_port'] as the default port when otherwise not provided. Use the opts key given by masters for the masters list, default is 'master' If parameter port is not None then uses the default port given by port Returns a list of host address dicts of the form [ { 'external': (host,port), 'internal': (host, port) }, ... ] When only one address is provided it is assigned to the external address field When not provided the internal address field is set to None. For a given master the syntax options are as follows: hostname [port] external: hostname [port] [internal: hostaddress [port]] Where the hostname string could be either an FQDN or host address in dotted number notation. master.example.com 10.0.2.110 And the hostadress is in dotted number notation The space delimited port is optional and if not provided a default is used. The internal address is optional and if not provided is set to None Examples showing the YAML in /etc/salt/master conf file: 1) Single host name string (fqdn or dotted address) a) master: me.example.com b) master: localhost c) master: 10.0.2.205 2) Single host name string with port a) master: me.example.com 4506 b) master: 10.0.2.205 4510 3) Single master with external and optional internal host addresses for nat in a dict master: external: me.example.com 4506 internal: 10.0.2.100 4506 3) One or host host names with optional ports in a list master: - me.example.com 4506 - you.example.com 4510 - 8.8.8.8 - they.example.com 4506 - 8.8.4.4 4506 4) One or more host name with external and optional internal host addresses for Nat in a list of dicts master: - external: me.example.com 4506 internal: 10.0.2.100 4506 - external: you.example.com 4506 internal: 10.0.2.101 4506 - external: we.example.com - they.example.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/daemons/__init__.py#L48-L197
[ "def is_non_string_sequence(obj):\n \"\"\"\n Returns True if obj is non-string sequence, False otherwise\n\n Future proof way that is compatible with both Python3 and Python2 to check\n for non string sequences.\n Assumes in Python3 that, basestring = (str, bytes)\n \"\"\"\n return not isinstance(obj, six.string_types) and isinstance(obj, Sequence)\n" ]
# -*- coding: utf-8 -*- ''' The daemons package is used to store implementations of the Salt Master and Minion enabling different transports. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python Libs import sys try: from collections.abc import Iterable, Sequence, Mapping except ImportError: from collections import Iterable, Sequence, Mapping import logging # Import Salt Libs from salt.ext import six log = logging.getLogger(__name__) if sys.version_info[0] == 3: six.string_types = (six.text_type, six.binary_type) def is_non_string_iterable(obj): """ Returns True if obj is non-string iterable, False otherwise Future proof way that is compatible with both Python3 and Python2 to check for non string iterables. Assumes in Python3 that, basestring = (str, bytes) """ return not isinstance(obj, six.string_types) and isinstance(obj, Iterable) def is_non_string_sequence(obj): """ Returns True if obj is non-string sequence, False otherwise Future proof way that is compatible with both Python3 and Python2 to check for non string sequences. Assumes in Python3 that, basestring = (str, bytes) """ return not isinstance(obj, six.string_types) and isinstance(obj, Sequence) def parse_hostname(hostname, default_port): ''' Parse hostname string and return a tuple of (host, port) If port missing in hostname string then use default_port If anything is not a valid then return None hostname should contain a host and an option space delimited port host port As an attempt to prevent foolish mistakes the parser also tries to identify the port when it is colon delimited not space delimited. As in host:port. This is problematic since IPV6 addresses may have colons in them. Consequently the use of colon delimited ports is strongly discouraged. An ipv6 address must have at least 2 colons. ''' try: host, sep, port = hostname.strip().rpartition(' ') if not port: # invalid nothing there return None if not host: # no space separated port, only host as port use default port host = port port = default_port # ipv6 must have two or more colons if host.count(':') == 1: # only one so may be using colon delimited port host, sep, port = host.rpartition(':') if not host: # colon but not host so invalid return None if not port: # colon but no port so use default port = default_port host = host.strip() try: port = int(port) except ValueError: return None except AttributeError: return None return (host, port)
saltstack/salt
salt/daemons/__init__.py
parse_hostname
python
def parse_hostname(hostname, default_port): ''' Parse hostname string and return a tuple of (host, port) If port missing in hostname string then use default_port If anything is not a valid then return None hostname should contain a host and an option space delimited port host port As an attempt to prevent foolish mistakes the parser also tries to identify the port when it is colon delimited not space delimited. As in host:port. This is problematic since IPV6 addresses may have colons in them. Consequently the use of colon delimited ports is strongly discouraged. An ipv6 address must have at least 2 colons. ''' try: host, sep, port = hostname.strip().rpartition(' ') if not port: # invalid nothing there return None if not host: # no space separated port, only host as port use default port host = port port = default_port # ipv6 must have two or more colons if host.count(':') == 1: # only one so may be using colon delimited port host, sep, port = host.rpartition(':') if not host: # colon but not host so invalid return None if not port: # colon but no port so use default port = default_port host = host.strip() try: port = int(port) except ValueError: return None except AttributeError: return None return (host, port)
Parse hostname string and return a tuple of (host, port) If port missing in hostname string then use default_port If anything is not a valid then return None hostname should contain a host and an option space delimited port host port As an attempt to prevent foolish mistakes the parser also tries to identify the port when it is colon delimited not space delimited. As in host:port. This is problematic since IPV6 addresses may have colons in them. Consequently the use of colon delimited ports is strongly discouraged. An ipv6 address must have at least 2 colons.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/daemons/__init__.py#L200-L240
null
# -*- coding: utf-8 -*- ''' The daemons package is used to store implementations of the Salt Master and Minion enabling different transports. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python Libs import sys try: from collections.abc import Iterable, Sequence, Mapping except ImportError: from collections import Iterable, Sequence, Mapping import logging # Import Salt Libs from salt.ext import six log = logging.getLogger(__name__) if sys.version_info[0] == 3: six.string_types = (six.text_type, six.binary_type) def is_non_string_iterable(obj): """ Returns True if obj is non-string iterable, False otherwise Future proof way that is compatible with both Python3 and Python2 to check for non string iterables. Assumes in Python3 that, basestring = (str, bytes) """ return not isinstance(obj, six.string_types) and isinstance(obj, Iterable) def is_non_string_sequence(obj): """ Returns True if obj is non-string sequence, False otherwise Future proof way that is compatible with both Python3 and Python2 to check for non string sequences. Assumes in Python3 that, basestring = (str, bytes) """ return not isinstance(obj, six.string_types) and isinstance(obj, Sequence) def extract_masters(opts, masters='master', port=None, raise_if_empty=True): ''' Parses opts and generates a list of master (host,port) addresses. By default looks for list of masters in opts['master'] and uses opts['master_port'] as the default port when otherwise not provided. Use the opts key given by masters for the masters list, default is 'master' If parameter port is not None then uses the default port given by port Returns a list of host address dicts of the form [ { 'external': (host,port), 'internal': (host, port) }, ... ] When only one address is provided it is assigned to the external address field When not provided the internal address field is set to None. For a given master the syntax options are as follows: hostname [port] external: hostname [port] [internal: hostaddress [port]] Where the hostname string could be either an FQDN or host address in dotted number notation. master.example.com 10.0.2.110 And the hostadress is in dotted number notation The space delimited port is optional and if not provided a default is used. The internal address is optional and if not provided is set to None Examples showing the YAML in /etc/salt/master conf file: 1) Single host name string (fqdn or dotted address) a) master: me.example.com b) master: localhost c) master: 10.0.2.205 2) Single host name string with port a) master: me.example.com 4506 b) master: 10.0.2.205 4510 3) Single master with external and optional internal host addresses for nat in a dict master: external: me.example.com 4506 internal: 10.0.2.100 4506 3) One or host host names with optional ports in a list master: - me.example.com 4506 - you.example.com 4510 - 8.8.8.8 - they.example.com 4506 - 8.8.4.4 4506 4) One or more host name with external and optional internal host addresses for Nat in a list of dicts master: - external: me.example.com 4506 internal: 10.0.2.100 4506 - external: you.example.com 4506 internal: 10.0.2.101 4506 - external: we.example.com - they.example.com ''' if port is not None: master_port = opts.get(port) else: master_port = opts.get('master_port') try: master_port = int(master_port) except ValueError: master_port = None if not master_port: emsg = "Invalid or missing opts['master_port']." log.error(emsg) raise ValueError(emsg) entries = opts.get(masters, []) if not entries: emsg = "Invalid or missing opts['{0}'].".format(masters) log.error(emsg) if raise_if_empty: raise ValueError(emsg) hostages = [] # extract candidate hostage (hostname dict) from entries if is_non_string_sequence(entries): # multiple master addresses provided for entry in entries: if isinstance(entry, Mapping): # mapping external = entry.get('external', '') internal = entry.get('internal', '') hostages.append(dict(external=external, internal=internal)) elif isinstance(entry, six.string_types): # string external = entry internal = '' hostages.append(dict(external=external, internal=internal)) elif isinstance(entries, Mapping): # mapping external = entries.get('external', '') internal = entries.get('internal', '') hostages.append(dict(external=external, internal=internal)) elif isinstance(entries, six.string_types): # string external = entries internal = '' hostages.append(dict(external=external, internal=internal)) # now parse each hostname string for host and optional port masters = [] for hostage in hostages: external = hostage['external'] internal = hostage['internal'] if external: external = parse_hostname(external, master_port) if not external: continue # must have a valid external host address internal = parse_hostname(internal, master_port) masters.append(dict(external=external, internal=internal)) return masters
saltstack/salt
salt/modules/ciscoconfparse_mod.py
find_objects
python
def find_objects(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the line objects that match the expression in the ``regex`` argument. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt', regex='Gigabit') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects(regex) return lines
Return all the line objects that match the expression in the ``regex`` argument. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt', regex='Gigabit') for obj in objects: print(obj.text)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ciscoconfparse_mod.py#L71-L111
[ "def _get_ccp(config=None, config_path=None, saltenv='base'):\n '''\n '''\n if config_path:\n config = __salt__['cp.get_file_str'](config_path, saltenv=saltenv)\n if config is False:\n raise SaltException('{} is not available'.format(config_path))\n if isinstance(config, six.string_types):\n config = config.splitlines()\n ccp = ciscoconfparse.CiscoConfParse(config)\n return ccp\n" ]
# -*- coding: utf-8 -*- ''' Execution module for `ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_ .. versionadded:: 2019.2.0 This module can be used for basic configuration parsing, audit or validation for a variety of network platforms having Cisco IOS style configuration (one space indentation), including: Cisco IOS, Cisco Nexus, Cisco IOS-XR, Cisco IOS-XR, Cisco ASA, Arista EOS, Brocade, HP Switches, Dell PowerConnect Switches, or Extreme Networks devices. In newer versions, ``ciscoconfparse`` provides support for brace-delimited configuration style as well, for platforms such as: Juniper Junos, Palo Alto, or F5 Networks. See http://www.pennington.net/py/ciscoconfparse/index.html for further details. :depends: ciscoconfparse This module depends on the Python library with the same name, ``ciscoconfparse`` - to install execute: ``pip install ciscoconfparse``. ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function # Import Salt modules from salt.ext import six from salt.exceptions import SaltException try: import ciscoconfparse HAS_CISCOCONFPARSE = True except ImportError: HAS_CISCOCONFPARSE = False # ------------------------------------------------------------------------------ # module properties # ------------------------------------------------------------------------------ __virtualname__ = 'ciscoconfparse' # ------------------------------------------------------------------------------ # property functions # ------------------------------------------------------------------------------ def __virtual__(): return HAS_CISCOCONFPARSE # ------------------------------------------------------------------------------ # helper functions -- will not be exported # ------------------------------------------------------------------------------ def _get_ccp(config=None, config_path=None, saltenv='base'): ''' ''' if config_path: config = __salt__['cp.get_file_str'](config_path, saltenv=saltenv) if config is False: raise SaltException('{} is not available'.format(config_path)) if isinstance(config, six.string_types): config = config.splitlines() ccp = ciscoconfparse.CiscoConfParse(config) return ccp # ------------------------------------------------------------------------------ # callable functions # ------------------------------------------------------------------------------ def find_lines(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the lines (as text) that match the expression in the ``regex`` argument. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines config_path=https://bit.ly/2mAdq7z regex='ip address' Output example: .. code-block:: text cisco-ios-router: - ip address dhcp - ip address 172.20.0.1 255.255.255.0 - no ip address ''' lines = find_objects(config=config, config_path=config_path, regex=regex, saltenv=saltenv) return [line.text for line in lines] def find_objects_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Parse through the children of all parent lines matching ``parent_regex``, and return a list of child objects, which matched the ``child_regex``. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_w_child <salt.ciscoconfparse_mod.find_lines_w_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_w_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_w_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def find_lines_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): r''' Return a list of parent lines (as text) matching the regular expression ``parent_regex`` that have children lines matching ``child_regex``. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+' ''' lines = find_objects_w_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines] def find_objects_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def find_lines_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` lines as text, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` text lines will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_wo_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' ''' lines = find_objects_wo_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines] def filter_lines(config=None, config_path=None, parent_regex=None, child_regex=None, saltenv='base'): ''' Return a list of detailed matches, for the configuration blocks (parent-child relationship) whose parent respects the regular expressions configured via the ``parent_regex`` argument, and the child matches the ``child_regex`` regular expression. The result is a list of dictionaries with the following keys: - ``match``: a boolean value that tells whether ``child_regex`` matched any children lines. - ``parent``: the parent line (as text). - ``child``: the child line (as text). If no child line matched, this field will be ``None``. Note that the return list contains the elements that matched the parent condition, the ``parent_regex`` regular expression. Therefore, the ``parent`` field will always have a valid value, while ``match`` and ``child`` may default to ``False`` and ``None`` respectively when there is not child match. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.filter_lines config_path=https://bit.ly/2mAdq7z parent_regex='Gigabit' child_regex='shutdown' Example output (for the example above): .. code-block:: python [ { 'parent': 'interface GigabitEthernet1', 'match': False, 'child': None }, { 'parent': 'interface GigabitEthernet2', 'match': True, 'child': ' shutdown' }, { 'parent': 'interface GigabitEthernet3', 'match': True, 'child': ' shutdown' } ] ''' ret = [] ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) parent_lines = ccp.find_objects(parent_regex) for parent_line in parent_lines: child_lines = parent_line.re_search_children(child_regex) if child_lines: for child_line in child_lines: ret.append({ 'match': True, 'parent': parent_line.text, 'child': child_line.text }) else: ret.append({ 'match': False, 'parent': parent_line.text, 'child': None }) return ret
saltstack/salt
salt/modules/ciscoconfparse_mod.py
find_lines
python
def find_lines(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the lines (as text) that match the expression in the ``regex`` argument. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines config_path=https://bit.ly/2mAdq7z regex='ip address' Output example: .. code-block:: text cisco-ios-router: - ip address dhcp - ip address 172.20.0.1 255.255.255.0 - no ip address ''' lines = find_objects(config=config, config_path=config_path, regex=regex, saltenv=saltenv) return [line.text for line in lines]
Return all the lines (as text) that match the expression in the ``regex`` argument. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines config_path=https://bit.ly/2mAdq7z regex='ip address' Output example: .. code-block:: text cisco-ios-router: - ip address dhcp - ip address 172.20.0.1 255.255.255.0 - no ip address
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ciscoconfparse_mod.py#L114-L156
[ "def find_objects(config=None, config_path=None, regex=None, saltenv='base'):\n '''\n Return all the line objects that match the expression in the ``regex``\n argument.\n\n .. warning::\n This function is mostly valuable when invoked from other Salt\n components (i.e., execution modules, states, templates etc.). For CLI\n usage, please consider using\n :py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>`\n\n config\n The configuration sent as text.\n\n .. note::\n This argument is ignored when ``config_path`` is specified.\n\n config_path\n The absolute or remote path to the file with the configuration to be\n parsed. This argument supports the usual Salt filesystem URIs, e.g.,\n ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc.\n\n regex\n The regular expression to match the lines against.\n\n saltenv: ``base``\n Salt fileserver environment from which to retrieve the file. This\n argument is ignored when ``config_path`` is not a ``salt://`` URL.\n\n Usage example:\n\n .. code-block:: python\n\n objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt',\n regex='Gigabit')\n for obj in objects:\n print(obj.text)\n '''\n ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv)\n lines = ccp.find_objects(regex)\n return lines\n" ]
# -*- coding: utf-8 -*- ''' Execution module for `ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_ .. versionadded:: 2019.2.0 This module can be used for basic configuration parsing, audit or validation for a variety of network platforms having Cisco IOS style configuration (one space indentation), including: Cisco IOS, Cisco Nexus, Cisco IOS-XR, Cisco IOS-XR, Cisco ASA, Arista EOS, Brocade, HP Switches, Dell PowerConnect Switches, or Extreme Networks devices. In newer versions, ``ciscoconfparse`` provides support for brace-delimited configuration style as well, for platforms such as: Juniper Junos, Palo Alto, or F5 Networks. See http://www.pennington.net/py/ciscoconfparse/index.html for further details. :depends: ciscoconfparse This module depends on the Python library with the same name, ``ciscoconfparse`` - to install execute: ``pip install ciscoconfparse``. ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function # Import Salt modules from salt.ext import six from salt.exceptions import SaltException try: import ciscoconfparse HAS_CISCOCONFPARSE = True except ImportError: HAS_CISCOCONFPARSE = False # ------------------------------------------------------------------------------ # module properties # ------------------------------------------------------------------------------ __virtualname__ = 'ciscoconfparse' # ------------------------------------------------------------------------------ # property functions # ------------------------------------------------------------------------------ def __virtual__(): return HAS_CISCOCONFPARSE # ------------------------------------------------------------------------------ # helper functions -- will not be exported # ------------------------------------------------------------------------------ def _get_ccp(config=None, config_path=None, saltenv='base'): ''' ''' if config_path: config = __salt__['cp.get_file_str'](config_path, saltenv=saltenv) if config is False: raise SaltException('{} is not available'.format(config_path)) if isinstance(config, six.string_types): config = config.splitlines() ccp = ciscoconfparse.CiscoConfParse(config) return ccp # ------------------------------------------------------------------------------ # callable functions # ------------------------------------------------------------------------------ def find_objects(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the line objects that match the expression in the ``regex`` argument. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt', regex='Gigabit') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects(regex) return lines def find_objects_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Parse through the children of all parent lines matching ``parent_regex``, and return a list of child objects, which matched the ``child_regex``. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_w_child <salt.ciscoconfparse_mod.find_lines_w_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_w_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_w_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def find_lines_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): r''' Return a list of parent lines (as text) matching the regular expression ``parent_regex`` that have children lines matching ``child_regex``. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+' ''' lines = find_objects_w_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines] def find_objects_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def find_lines_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` lines as text, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` text lines will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_wo_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' ''' lines = find_objects_wo_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines] def filter_lines(config=None, config_path=None, parent_regex=None, child_regex=None, saltenv='base'): ''' Return a list of detailed matches, for the configuration blocks (parent-child relationship) whose parent respects the regular expressions configured via the ``parent_regex`` argument, and the child matches the ``child_regex`` regular expression. The result is a list of dictionaries with the following keys: - ``match``: a boolean value that tells whether ``child_regex`` matched any children lines. - ``parent``: the parent line (as text). - ``child``: the child line (as text). If no child line matched, this field will be ``None``. Note that the return list contains the elements that matched the parent condition, the ``parent_regex`` regular expression. Therefore, the ``parent`` field will always have a valid value, while ``match`` and ``child`` may default to ``False`` and ``None`` respectively when there is not child match. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.filter_lines config_path=https://bit.ly/2mAdq7z parent_regex='Gigabit' child_regex='shutdown' Example output (for the example above): .. code-block:: python [ { 'parent': 'interface GigabitEthernet1', 'match': False, 'child': None }, { 'parent': 'interface GigabitEthernet2', 'match': True, 'child': ' shutdown' }, { 'parent': 'interface GigabitEthernet3', 'match': True, 'child': ' shutdown' } ] ''' ret = [] ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) parent_lines = ccp.find_objects(parent_regex) for parent_line in parent_lines: child_lines = parent_line.re_search_children(child_regex) if child_lines: for child_line in child_lines: ret.append({ 'match': True, 'parent': parent_line.text, 'child': child_line.text }) else: ret.append({ 'match': False, 'parent': parent_line.text, 'child': None }) return ret
saltstack/salt
salt/modules/ciscoconfparse_mod.py
find_lines_w_child
python
def find_lines_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): r''' Return a list of parent lines (as text) matching the regular expression ``parent_regex`` that have children lines matching ``child_regex``. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+' ''' lines = find_objects_w_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines]
r''' Return a list of parent lines (as text) matching the regular expression ``parent_regex`` that have children lines matching ``child_regex``. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ciscoconfparse_mod.py#L214-L261
[ "def find_objects_w_child(config=None,\n config_path=None,\n parent_regex=None,\n child_regex=None,\n ignore_ws=False,\n saltenv='base'):\n '''\n Parse through the children of all parent lines matching ``parent_regex``,\n and return a list of child objects, which matched the ``child_regex``.\n\n .. warning::\n This function is mostly valuable when invoked from other Salt\n components (i.e., execution modules, states, templates etc.). For CLI\n usage, please consider using\n :py:func:`ciscoconfparse.find_lines_w_child <salt.ciscoconfparse_mod.find_lines_w_child>`\n\n config\n The configuration sent as text.\n\n .. note::\n This argument is ignored when ``config_path`` is specified.\n\n config_path\n The absolute or remote path to the file with the configuration to be\n parsed. This argument supports the usual Salt filesystem URIs, e.g.,\n ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc.\n\n parent_regex\n The regular expression to match the parent lines against.\n\n child_regex\n The regular expression to match the child lines against.\n\n ignore_ws: ``False``\n Whether to ignore the white spaces.\n\n saltenv: ``base``\n Salt fileserver environment from which to retrieve the file. This\n argument is ignored when ``config_path`` is not a ``salt://`` URL.\n\n Usage example:\n\n .. code-block:: python\n\n objects = __salt__['ciscoconfparse.find_objects_w_child'](config_path='https://bit.ly/2mAdq7z',\n parent_regex='line con',\n child_regex='stopbits')\n for obj in objects:\n print(obj.text)\n '''\n ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv)\n lines = ccp.find_objects_w_child(parent_regex, child_regex, ignore_ws=ignore_ws)\n return lines\n" ]
# -*- coding: utf-8 -*- ''' Execution module for `ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_ .. versionadded:: 2019.2.0 This module can be used for basic configuration parsing, audit or validation for a variety of network platforms having Cisco IOS style configuration (one space indentation), including: Cisco IOS, Cisco Nexus, Cisco IOS-XR, Cisco IOS-XR, Cisco ASA, Arista EOS, Brocade, HP Switches, Dell PowerConnect Switches, or Extreme Networks devices. In newer versions, ``ciscoconfparse`` provides support for brace-delimited configuration style as well, for platforms such as: Juniper Junos, Palo Alto, or F5 Networks. See http://www.pennington.net/py/ciscoconfparse/index.html for further details. :depends: ciscoconfparse This module depends on the Python library with the same name, ``ciscoconfparse`` - to install execute: ``pip install ciscoconfparse``. ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function # Import Salt modules from salt.ext import six from salt.exceptions import SaltException try: import ciscoconfparse HAS_CISCOCONFPARSE = True except ImportError: HAS_CISCOCONFPARSE = False # ------------------------------------------------------------------------------ # module properties # ------------------------------------------------------------------------------ __virtualname__ = 'ciscoconfparse' # ------------------------------------------------------------------------------ # property functions # ------------------------------------------------------------------------------ def __virtual__(): return HAS_CISCOCONFPARSE # ------------------------------------------------------------------------------ # helper functions -- will not be exported # ------------------------------------------------------------------------------ def _get_ccp(config=None, config_path=None, saltenv='base'): ''' ''' if config_path: config = __salt__['cp.get_file_str'](config_path, saltenv=saltenv) if config is False: raise SaltException('{} is not available'.format(config_path)) if isinstance(config, six.string_types): config = config.splitlines() ccp = ciscoconfparse.CiscoConfParse(config) return ccp # ------------------------------------------------------------------------------ # callable functions # ------------------------------------------------------------------------------ def find_objects(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the line objects that match the expression in the ``regex`` argument. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt', regex='Gigabit') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects(regex) return lines def find_lines(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the lines (as text) that match the expression in the ``regex`` argument. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines config_path=https://bit.ly/2mAdq7z regex='ip address' Output example: .. code-block:: text cisco-ios-router: - ip address dhcp - ip address 172.20.0.1 255.255.255.0 - no ip address ''' lines = find_objects(config=config, config_path=config_path, regex=regex, saltenv=saltenv) return [line.text for line in lines] def find_objects_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Parse through the children of all parent lines matching ``parent_regex``, and return a list of child objects, which matched the ``child_regex``. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_w_child <salt.ciscoconfparse_mod.find_lines_w_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_w_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_w_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def find_objects_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def find_lines_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` lines as text, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` text lines will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_wo_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' ''' lines = find_objects_wo_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines] def filter_lines(config=None, config_path=None, parent_regex=None, child_regex=None, saltenv='base'): ''' Return a list of detailed matches, for the configuration blocks (parent-child relationship) whose parent respects the regular expressions configured via the ``parent_regex`` argument, and the child matches the ``child_regex`` regular expression. The result is a list of dictionaries with the following keys: - ``match``: a boolean value that tells whether ``child_regex`` matched any children lines. - ``parent``: the parent line (as text). - ``child``: the child line (as text). If no child line matched, this field will be ``None``. Note that the return list contains the elements that matched the parent condition, the ``parent_regex`` regular expression. Therefore, the ``parent`` field will always have a valid value, while ``match`` and ``child`` may default to ``False`` and ``None`` respectively when there is not child match. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.filter_lines config_path=https://bit.ly/2mAdq7z parent_regex='Gigabit' child_regex='shutdown' Example output (for the example above): .. code-block:: python [ { 'parent': 'interface GigabitEthernet1', 'match': False, 'child': None }, { 'parent': 'interface GigabitEthernet2', 'match': True, 'child': ' shutdown' }, { 'parent': 'interface GigabitEthernet3', 'match': True, 'child': ' shutdown' } ] ''' ret = [] ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) parent_lines = ccp.find_objects(parent_regex) for parent_line in parent_lines: child_lines = parent_line.re_search_children(child_regex) if child_lines: for child_line in child_lines: ret.append({ 'match': True, 'parent': parent_line.text, 'child': child_line.text }) else: ret.append({ 'match': False, 'parent': parent_line.text, 'child': None }) return ret
saltstack/salt
salt/modules/ciscoconfparse_mod.py
find_objects_wo_child
python
def find_objects_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines
Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ciscoconfparse_mod.py#L264-L319
[ "def _get_ccp(config=None, config_path=None, saltenv='base'):\n '''\n '''\n if config_path:\n config = __salt__['cp.get_file_str'](config_path, saltenv=saltenv)\n if config is False:\n raise SaltException('{} is not available'.format(config_path))\n if isinstance(config, six.string_types):\n config = config.splitlines()\n ccp = ciscoconfparse.CiscoConfParse(config)\n return ccp\n" ]
# -*- coding: utf-8 -*- ''' Execution module for `ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_ .. versionadded:: 2019.2.0 This module can be used for basic configuration parsing, audit or validation for a variety of network platforms having Cisco IOS style configuration (one space indentation), including: Cisco IOS, Cisco Nexus, Cisco IOS-XR, Cisco IOS-XR, Cisco ASA, Arista EOS, Brocade, HP Switches, Dell PowerConnect Switches, or Extreme Networks devices. In newer versions, ``ciscoconfparse`` provides support for brace-delimited configuration style as well, for platforms such as: Juniper Junos, Palo Alto, or F5 Networks. See http://www.pennington.net/py/ciscoconfparse/index.html for further details. :depends: ciscoconfparse This module depends on the Python library with the same name, ``ciscoconfparse`` - to install execute: ``pip install ciscoconfparse``. ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function # Import Salt modules from salt.ext import six from salt.exceptions import SaltException try: import ciscoconfparse HAS_CISCOCONFPARSE = True except ImportError: HAS_CISCOCONFPARSE = False # ------------------------------------------------------------------------------ # module properties # ------------------------------------------------------------------------------ __virtualname__ = 'ciscoconfparse' # ------------------------------------------------------------------------------ # property functions # ------------------------------------------------------------------------------ def __virtual__(): return HAS_CISCOCONFPARSE # ------------------------------------------------------------------------------ # helper functions -- will not be exported # ------------------------------------------------------------------------------ def _get_ccp(config=None, config_path=None, saltenv='base'): ''' ''' if config_path: config = __salt__['cp.get_file_str'](config_path, saltenv=saltenv) if config is False: raise SaltException('{} is not available'.format(config_path)) if isinstance(config, six.string_types): config = config.splitlines() ccp = ciscoconfparse.CiscoConfParse(config) return ccp # ------------------------------------------------------------------------------ # callable functions # ------------------------------------------------------------------------------ def find_objects(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the line objects that match the expression in the ``regex`` argument. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt', regex='Gigabit') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects(regex) return lines def find_lines(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the lines (as text) that match the expression in the ``regex`` argument. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines config_path=https://bit.ly/2mAdq7z regex='ip address' Output example: .. code-block:: text cisco-ios-router: - ip address dhcp - ip address 172.20.0.1 255.255.255.0 - no ip address ''' lines = find_objects(config=config, config_path=config_path, regex=regex, saltenv=saltenv) return [line.text for line in lines] def find_objects_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Parse through the children of all parent lines matching ``parent_regex``, and return a list of child objects, which matched the ``child_regex``. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_w_child <salt.ciscoconfparse_mod.find_lines_w_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_w_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_w_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def find_lines_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): r''' Return a list of parent lines (as text) matching the regular expression ``parent_regex`` that have children lines matching ``child_regex``. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+' ''' lines = find_objects_w_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines] def find_lines_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` lines as text, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` text lines will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_wo_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' ''' lines = find_objects_wo_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines] def filter_lines(config=None, config_path=None, parent_regex=None, child_regex=None, saltenv='base'): ''' Return a list of detailed matches, for the configuration blocks (parent-child relationship) whose parent respects the regular expressions configured via the ``parent_regex`` argument, and the child matches the ``child_regex`` regular expression. The result is a list of dictionaries with the following keys: - ``match``: a boolean value that tells whether ``child_regex`` matched any children lines. - ``parent``: the parent line (as text). - ``child``: the child line (as text). If no child line matched, this field will be ``None``. Note that the return list contains the elements that matched the parent condition, the ``parent_regex`` regular expression. Therefore, the ``parent`` field will always have a valid value, while ``match`` and ``child`` may default to ``False`` and ``None`` respectively when there is not child match. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.filter_lines config_path=https://bit.ly/2mAdq7z parent_regex='Gigabit' child_regex='shutdown' Example output (for the example above): .. code-block:: python [ { 'parent': 'interface GigabitEthernet1', 'match': False, 'child': None }, { 'parent': 'interface GigabitEthernet2', 'match': True, 'child': ' shutdown' }, { 'parent': 'interface GigabitEthernet3', 'match': True, 'child': ' shutdown' } ] ''' ret = [] ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) parent_lines = ccp.find_objects(parent_regex) for parent_line in parent_lines: child_lines = parent_line.re_search_children(child_regex) if child_lines: for child_line in child_lines: ret.append({ 'match': True, 'parent': parent_line.text, 'child': child_line.text }) else: ret.append({ 'match': False, 'parent': parent_line.text, 'child': None }) return ret
saltstack/salt
salt/modules/ciscoconfparse_mod.py
find_lines_wo_child
python
def find_lines_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` lines as text, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` text lines will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_wo_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' ''' lines = find_objects_wo_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines]
Return a list of parent ``ciscoconfparse.IOSCfgLine`` lines as text, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` text lines will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_wo_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ciscoconfparse_mod.py#L322-L371
[ "def find_objects_wo_child(config=None,\n config_path=None,\n parent_regex=None,\n child_regex=None,\n ignore_ws=False,\n saltenv='base'):\n '''\n Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched\n the ``parent_regex`` and whose children did *not* match ``child_regex``.\n Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For\n simplicity, this method only finds oldest ancestors without immediate\n children that match.\n\n .. warning::\n This function is mostly valuable when invoked from other Salt\n components (i.e., execution modules, states, templates etc.). For CLI\n usage, please consider using\n :py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>`\n\n config\n The configuration sent as text.\n\n .. note::\n This argument is ignored when ``config_path`` is specified.\n\n config_path\n The absolute or remote path to the file with the configuration to be\n parsed. This argument supports the usual Salt filesystem URIs, e.g.,\n ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc.\n\n parent_regex\n The regular expression to match the parent lines against.\n\n child_regex\n The regular expression to match the child lines against.\n\n ignore_ws: ``False``\n Whether to ignore the white spaces.\n\n saltenv: ``base``\n Salt fileserver environment from which to retrieve the file. This\n argument is ignored when ``config_path`` is not a ``salt://`` URL.\n\n Usage example:\n\n .. code-block:: python\n\n objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z',\n parent_regex='line con',\n child_regex='stopbits')\n for obj in objects:\n print(obj.text)\n '''\n ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv)\n lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws)\n return lines\n" ]
# -*- coding: utf-8 -*- ''' Execution module for `ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_ .. versionadded:: 2019.2.0 This module can be used for basic configuration parsing, audit or validation for a variety of network platforms having Cisco IOS style configuration (one space indentation), including: Cisco IOS, Cisco Nexus, Cisco IOS-XR, Cisco IOS-XR, Cisco ASA, Arista EOS, Brocade, HP Switches, Dell PowerConnect Switches, or Extreme Networks devices. In newer versions, ``ciscoconfparse`` provides support for brace-delimited configuration style as well, for platforms such as: Juniper Junos, Palo Alto, or F5 Networks. See http://www.pennington.net/py/ciscoconfparse/index.html for further details. :depends: ciscoconfparse This module depends on the Python library with the same name, ``ciscoconfparse`` - to install execute: ``pip install ciscoconfparse``. ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function # Import Salt modules from salt.ext import six from salt.exceptions import SaltException try: import ciscoconfparse HAS_CISCOCONFPARSE = True except ImportError: HAS_CISCOCONFPARSE = False # ------------------------------------------------------------------------------ # module properties # ------------------------------------------------------------------------------ __virtualname__ = 'ciscoconfparse' # ------------------------------------------------------------------------------ # property functions # ------------------------------------------------------------------------------ def __virtual__(): return HAS_CISCOCONFPARSE # ------------------------------------------------------------------------------ # helper functions -- will not be exported # ------------------------------------------------------------------------------ def _get_ccp(config=None, config_path=None, saltenv='base'): ''' ''' if config_path: config = __salt__['cp.get_file_str'](config_path, saltenv=saltenv) if config is False: raise SaltException('{} is not available'.format(config_path)) if isinstance(config, six.string_types): config = config.splitlines() ccp = ciscoconfparse.CiscoConfParse(config) return ccp # ------------------------------------------------------------------------------ # callable functions # ------------------------------------------------------------------------------ def find_objects(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the line objects that match the expression in the ``regex`` argument. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt', regex='Gigabit') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects(regex) return lines def find_lines(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the lines (as text) that match the expression in the ``regex`` argument. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines config_path=https://bit.ly/2mAdq7z regex='ip address' Output example: .. code-block:: text cisco-ios-router: - ip address dhcp - ip address 172.20.0.1 255.255.255.0 - no ip address ''' lines = find_objects(config=config, config_path=config_path, regex=regex, saltenv=saltenv) return [line.text for line in lines] def find_objects_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Parse through the children of all parent lines matching ``parent_regex``, and return a list of child objects, which matched the ``child_regex``. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_w_child <salt.ciscoconfparse_mod.find_lines_w_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_w_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_w_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def find_lines_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): r''' Return a list of parent lines (as text) matching the regular expression ``parent_regex`` that have children lines matching ``child_regex``. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+' ''' lines = find_objects_w_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines] def find_objects_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def filter_lines(config=None, config_path=None, parent_regex=None, child_regex=None, saltenv='base'): ''' Return a list of detailed matches, for the configuration blocks (parent-child relationship) whose parent respects the regular expressions configured via the ``parent_regex`` argument, and the child matches the ``child_regex`` regular expression. The result is a list of dictionaries with the following keys: - ``match``: a boolean value that tells whether ``child_regex`` matched any children lines. - ``parent``: the parent line (as text). - ``child``: the child line (as text). If no child line matched, this field will be ``None``. Note that the return list contains the elements that matched the parent condition, the ``parent_regex`` regular expression. Therefore, the ``parent`` field will always have a valid value, while ``match`` and ``child`` may default to ``False`` and ``None`` respectively when there is not child match. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.filter_lines config_path=https://bit.ly/2mAdq7z parent_regex='Gigabit' child_regex='shutdown' Example output (for the example above): .. code-block:: python [ { 'parent': 'interface GigabitEthernet1', 'match': False, 'child': None }, { 'parent': 'interface GigabitEthernet2', 'match': True, 'child': ' shutdown' }, { 'parent': 'interface GigabitEthernet3', 'match': True, 'child': ' shutdown' } ] ''' ret = [] ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) parent_lines = ccp.find_objects(parent_regex) for parent_line in parent_lines: child_lines = parent_line.re_search_children(child_regex) if child_lines: for child_line in child_lines: ret.append({ 'match': True, 'parent': parent_line.text, 'child': child_line.text }) else: ret.append({ 'match': False, 'parent': parent_line.text, 'child': None }) return ret
saltstack/salt
salt/modules/ciscoconfparse_mod.py
filter_lines
python
def filter_lines(config=None, config_path=None, parent_regex=None, child_regex=None, saltenv='base'): ''' Return a list of detailed matches, for the configuration blocks (parent-child relationship) whose parent respects the regular expressions configured via the ``parent_regex`` argument, and the child matches the ``child_regex`` regular expression. The result is a list of dictionaries with the following keys: - ``match``: a boolean value that tells whether ``child_regex`` matched any children lines. - ``parent``: the parent line (as text). - ``child``: the child line (as text). If no child line matched, this field will be ``None``. Note that the return list contains the elements that matched the parent condition, the ``parent_regex`` regular expression. Therefore, the ``parent`` field will always have a valid value, while ``match`` and ``child`` may default to ``False`` and ``None`` respectively when there is not child match. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.filter_lines config_path=https://bit.ly/2mAdq7z parent_regex='Gigabit' child_regex='shutdown' Example output (for the example above): .. code-block:: python [ { 'parent': 'interface GigabitEthernet1', 'match': False, 'child': None }, { 'parent': 'interface GigabitEthernet2', 'match': True, 'child': ' shutdown' }, { 'parent': 'interface GigabitEthernet3', 'match': True, 'child': ' shutdown' } ] ''' ret = [] ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) parent_lines = ccp.find_objects(parent_regex) for parent_line in parent_lines: child_lines = parent_line.re_search_children(child_regex) if child_lines: for child_line in child_lines: ret.append({ 'match': True, 'parent': parent_line.text, 'child': child_line.text }) else: ret.append({ 'match': False, 'parent': parent_line.text, 'child': None }) return ret
Return a list of detailed matches, for the configuration blocks (parent-child relationship) whose parent respects the regular expressions configured via the ``parent_regex`` argument, and the child matches the ``child_regex`` regular expression. The result is a list of dictionaries with the following keys: - ``match``: a boolean value that tells whether ``child_regex`` matched any children lines. - ``parent``: the parent line (as text). - ``child``: the child line (as text). If no child line matched, this field will be ``None``. Note that the return list contains the elements that matched the parent condition, the ``parent_regex`` regular expression. Therefore, the ``parent`` field will always have a valid value, while ``match`` and ``child`` may default to ``False`` and ``None`` respectively when there is not child match. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.filter_lines config_path=https://bit.ly/2mAdq7z parent_regex='Gigabit' child_regex='shutdown' Example output (for the example above): .. code-block:: python [ { 'parent': 'interface GigabitEthernet1', 'match': False, 'child': None }, { 'parent': 'interface GigabitEthernet2', 'match': True, 'child': ' shutdown' }, { 'parent': 'interface GigabitEthernet3', 'match': True, 'child': ' shutdown' } ]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ciscoconfparse_mod.py#L374-L443
[ "def _get_ccp(config=None, config_path=None, saltenv='base'):\n '''\n '''\n if config_path:\n config = __salt__['cp.get_file_str'](config_path, saltenv=saltenv)\n if config is False:\n raise SaltException('{} is not available'.format(config_path))\n if isinstance(config, six.string_types):\n config = config.splitlines()\n ccp = ciscoconfparse.CiscoConfParse(config)\n return ccp\n" ]
# -*- coding: utf-8 -*- ''' Execution module for `ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_ .. versionadded:: 2019.2.0 This module can be used for basic configuration parsing, audit or validation for a variety of network platforms having Cisco IOS style configuration (one space indentation), including: Cisco IOS, Cisco Nexus, Cisco IOS-XR, Cisco IOS-XR, Cisco ASA, Arista EOS, Brocade, HP Switches, Dell PowerConnect Switches, or Extreme Networks devices. In newer versions, ``ciscoconfparse`` provides support for brace-delimited configuration style as well, for platforms such as: Juniper Junos, Palo Alto, or F5 Networks. See http://www.pennington.net/py/ciscoconfparse/index.html for further details. :depends: ciscoconfparse This module depends on the Python library with the same name, ``ciscoconfparse`` - to install execute: ``pip install ciscoconfparse``. ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function # Import Salt modules from salt.ext import six from salt.exceptions import SaltException try: import ciscoconfparse HAS_CISCOCONFPARSE = True except ImportError: HAS_CISCOCONFPARSE = False # ------------------------------------------------------------------------------ # module properties # ------------------------------------------------------------------------------ __virtualname__ = 'ciscoconfparse' # ------------------------------------------------------------------------------ # property functions # ------------------------------------------------------------------------------ def __virtual__(): return HAS_CISCOCONFPARSE # ------------------------------------------------------------------------------ # helper functions -- will not be exported # ------------------------------------------------------------------------------ def _get_ccp(config=None, config_path=None, saltenv='base'): ''' ''' if config_path: config = __salt__['cp.get_file_str'](config_path, saltenv=saltenv) if config is False: raise SaltException('{} is not available'.format(config_path)) if isinstance(config, six.string_types): config = config.splitlines() ccp = ciscoconfparse.CiscoConfParse(config) return ccp # ------------------------------------------------------------------------------ # callable functions # ------------------------------------------------------------------------------ def find_objects(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the line objects that match the expression in the ``regex`` argument. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt', regex='Gigabit') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects(regex) return lines def find_lines(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the lines (as text) that match the expression in the ``regex`` argument. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines config_path=https://bit.ly/2mAdq7z regex='ip address' Output example: .. code-block:: text cisco-ios-router: - ip address dhcp - ip address 172.20.0.1 255.255.255.0 - no ip address ''' lines = find_objects(config=config, config_path=config_path, regex=regex, saltenv=saltenv) return [line.text for line in lines] def find_objects_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Parse through the children of all parent lines matching ``parent_regex``, and return a list of child objects, which matched the ``child_regex``. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_w_child <salt.ciscoconfparse_mod.find_lines_w_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_w_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_w_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def find_lines_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): r''' Return a list of parent lines (as text) matching the regular expression ``parent_regex`` that have children lines matching ``child_regex``. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+' ''' lines = find_objects_w_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines] def find_objects_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def find_lines_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` lines as text, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` text lines will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_wo_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' ''' lines = find_objects_wo_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines]
saltstack/salt
salt/states/tuned.py
profile
python
def profile(name): ''' This state module allows you to modify system tuned parameters Example tuned.sls file to set profile to virtual-guest tuned: tuned: - profile - name: virtual-guest name tuned profile name to set the system to To see a valid list of states call execution module: :py:func:`tuned.list <salt.modules.tuned.list_>` ''' # create data-structure to return with default value ret = {'name': '', 'changes': {}, 'result': False, 'comment': ''} ret[name] = name profile = name # get the current state of tuned-adm current_state = __salt__['tuned.active']() valid_profiles = __salt__['tuned.list']() # check valid profiles, and return error if profile name is not valid if profile not in valid_profiles: raise salt.exceptions.SaltInvocationError('Invalid Profile Name') # if current state is same as requested state, return without doing much if profile in current_state: ret['result'] = True ret['comment'] = 'System already in the correct state' return ret # test mode if __opts__['test'] is True: ret['comment'] = 'The state of "{0}" will be changed.'.format( current_state) ret['changes'] = { 'old': current_state, 'new': 'Profile will be set to {0}'.format(profile), } # return None when testing ret['result'] = None return ret # we come to this stage if current state is different that requested state # we there have to set the new state request new_state = __salt__['tuned.profile'](profile) # create the comment data structure ret['comment'] = 'The state of "{0}" was changed!'.format(profile) # fill in the ret data structure ret['changes'] = { 'old': current_state, 'new': new_state, } ret['result'] = True # return with the dictionary data structure return ret
This state module allows you to modify system tuned parameters Example tuned.sls file to set profile to virtual-guest tuned: tuned: - profile - name: virtual-guest name tuned profile name to set the system to To see a valid list of states call execution module: :py:func:`tuned.list <salt.modules.tuned.list_>`
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/tuned.py#L18-L86
null
# -*- coding: utf-8 -*- ''' Interface to Red Hat tuned-adm module :maintainer: Syed Ali <alicsyed@gmail.com> :maturity: new :depends: cmd.run :platform: Linux ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function # Import Salt libs import salt.exceptions def off(name=None): ''' Turns 'tuned' off. Example tuned.sls file for turning tuned off: tuned: tuned.off: [] To see a valid list of states call execution module: :py:func:`tuned.list <salt.modules.tuned.list_>` ''' # create data-structure to return with default value ret = {'name': 'off', 'changes': {}, 'result': False, 'comment': 'off'} # check the current state of tuned current_state = __salt__['tuned.active']() # if profile is already off, then don't do anything if current_state == 'off': ret['result'] = True ret['comment'] = 'System already in the correct state' return ret # test mode if __opts__['test'] is True: ret['comment'] = 'The state of "{0}" will be changed.'.format( current_state) ret['changes'] = { 'old': current_state, 'new': 'Profile will be set to off', } # return None when testing ret['result'] = None return ret # actually execute the off statement if __salt__['tuned.off'](): ret['result'] = True ret['changes'] = { 'old': current_state, 'new': 'off', } return ret
saltstack/salt
salt/modules/napalm_probes.py
delete_probes
python
def delete_probes(probes, test=False, commit=True, **kwargs): # pylint: disable=unused-argument ''' Removes RPM/SLA probes from the network device. Calls the configuration template 'delete_probes' from the NAPALM library, providing as input a rich formatted dictionary with the configuration details of the probes to be removed from the configuration of the device. :param probes: Dictionary with a similar format as the output dictionary of the function config(), where the details are not necessary. :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return: A dictionary having the following keys: - result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) - comment (str): a message for the user - already_configured (bool): flag to check if there were no changes applied - diff (str): returns the config changes applied Input example: .. code-block:: python probes = { 'existing_probe':{ 'existing_test1': {}, 'existing_test2': {} } } ''' return __salt__['net.load_template']('delete_probes', probes=probes, test=test, commit=commit, inherit_napalm_device=napalm_device)
Removes RPM/SLA probes from the network device. Calls the configuration template 'delete_probes' from the NAPALM library, providing as input a rich formatted dictionary with the configuration details of the probes to be removed from the configuration of the device. :param probes: Dictionary with a similar format as the output dictionary of the function config(), where the details are not necessary. :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return: A dictionary having the following keys: - result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) - comment (str): a message for the user - already_configured (bool): flag to check if there were no changes applied - diff (str): returns the config changes applied Input example: .. code-block:: python probes = { 'existing_probe':{ 'existing_test1': {}, 'existing_test2': {} } }
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_probes.py#L273-L320
null
# -*- coding: utf-8 -*- ''' NAPALM Probes ============= Manages RPM/SLA probes on the network device. :codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com> :maturity: new :depends: napalm :platform: unix Dependencies ------------ - :mod:`napalm proxy minion <salt.proxy.napalm>` - :mod:`NET basic features <salt.modules.napalm_network>` .. seealso:: :mod:`Probes configuration management state <salt.states.probes>` .. versionadded:: 2016.11.0 ''' from __future__ import absolute_import, unicode_literals, print_function # Import python lib import logging log = logging.getLogger(__file__) # import NAPALM utils import salt.utils.napalm from salt.utils.napalm import proxy_napalm_wrap # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'probes' __proxyenabled__ = ['napalm'] # uses NAPALM-based proxy to interact with network devices # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' NAPALM library must be installed for this module to work and run in a (proxy) minion. ''' return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__) # ---------------------------------------------------------------------------------------------------------------------- # helper functions -- will not be exported # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- @proxy_napalm_wrap def config(**kwargs): # pylint: disable=unused-argument ''' Returns the configuration of the RPM probes. :return: A dictionary containing the configuration of the RPM/SLA probes. CLI Example: .. code-block:: bash salt '*' probes.config Output Example: .. code-block:: python { 'probe1':{ 'test1': { 'probe_type' : 'icmp-ping', 'target' : '192.168.0.1', 'source' : '192.168.0.2', 'probe_count' : 13, 'test_interval': 3 }, 'test2': { 'probe_type' : 'http-ping', 'target' : '172.17.17.1', 'source' : '192.17.17.2', 'probe_count' : 5, 'test_interval': 60 } } } ''' return salt.utils.napalm.call( napalm_device, # pylint: disable=undefined-variable 'get_probes_config', **{ } ) @proxy_napalm_wrap def results(**kwargs): # pylint: disable=unused-argument ''' Provides the results of the measurements of the RPM/SLA probes. :return a dictionary with the results of the probes. CLI Example: .. code-block:: bash salt '*' probes.results Output example: .. code-block:: python { 'probe1': { 'test1': { 'last_test_min_delay' : 63.120, 'global_test_min_delay' : 62.912, 'current_test_avg_delay': 63.190, 'global_test_max_delay' : 177.349, 'current_test_max_delay': 63.302, 'global_test_avg_delay' : 63.802, 'last_test_avg_delay' : 63.438, 'last_test_max_delay' : 65.356, 'probe_type' : 'icmp-ping', 'rtt' : 63.138, 'last_test_loss' : 0, 'round_trip_jitter' : -59.0, 'target' : '192.168.0.1', 'source' : '192.168.0.2', 'probe_count' : 15, 'current_test_min_delay': 63.138 }, 'test2': { 'last_test_min_delay' : 176.384, 'global_test_min_delay' : 169.226, 'current_test_avg_delay': 177.098, 'global_test_max_delay' : 292.628, 'current_test_max_delay': 180.055, 'global_test_avg_delay' : 177.959, 'last_test_avg_delay' : 177.178, 'last_test_max_delay' : 184.671, 'probe_type' : 'icmp-ping', 'rtt' : 176.449, 'last_test_loss' : 0, 'round_trip_jitter' : -34.0, 'target' : '172.17.17.1', 'source' : '172.17.17.2', 'probe_count' : 15, 'current_test_min_delay': 176.402 } } } ''' return salt.utils.napalm.call( napalm_device, # pylint: disable=undefined-variable 'get_probes_results', **{ } ) @proxy_napalm_wrap def set_probes(probes, test=False, commit=True, **kwargs): # pylint: disable=unused-argument ''' Configures RPM/SLA probes on the device. Calls the configuration template 'set_probes' from the NAPALM library, providing as input a rich formatted dictionary with the configuration details of the probes to be configured. :param probes: Dictionary formatted as the output of the function config() :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return a dictionary having the following keys: * result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) * comment (str): a message for the user * already_configured (bool): flag to check if there were no changes applied * diff (str): returns the config changes applied Input example - via state/script: .. code-block:: python probes = { 'new_probe':{ 'new_test1': { 'probe_type' : 'icmp-ping', 'target' : '192.168.0.1', 'source' : '192.168.0.2', 'probe_count' : 13, 'test_interval': 3 }, 'new_test2': { 'probe_type' : 'http-ping', 'target' : '172.17.17.1', 'source' : '192.17.17.2', 'probe_count' : 5, 'test_interval': 60 } } } set_probes(probes) CLI Example - to push cahnges on the fly (not recommended): .. code-block:: bash salt 'junos_minion' probes.set_probes "{'new_probe':{'new_test1':{'probe_type':'icmp-ping',\ 'target':'192.168.0.1','source':'192.168.0.2','probe_count':13,'test_interval':3}}}" test=True Output example - for the CLI example above: .. code-block:: yaml junos_minion: ---------- already_configured: False comment: Configuration discarded. diff: [edit services rpm] probe transit { ... } + probe new_probe { + test new_test1 { + probe-type icmp-ping; + target address 192.168.0.1; + probe-count 13; + test-interval 3; + source-address 192.168.0.2; + } + } result: True ''' return __salt__['net.load_template']('set_probes', probes=probes, test=test, commit=commit, inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable @proxy_napalm_wrap # pylint: disable=undefined-variable @proxy_napalm_wrap def schedule_probes(probes, test=False, commit=True, **kwargs): # pylint: disable=unused-argument ''' Will schedule the probes. On Cisco devices, it is not enough to define the probes, it is also necessary to schedule them. This function calls the configuration template ``schedule_probes`` from the NAPALM library, providing as input a rich formatted dictionary with the names of the probes and the tests to be scheduled. :param probes: Dictionary with a similar format as the output dictionary of the function config(), where the details are not necessary. :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return: a dictionary having the following keys: - result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) - comment (str): a message for the user - already_configured (bool): flag to check if there were no changes applied - diff (str): returns the config changes applied Input example: .. code-block:: python probes = { 'new_probe':{ 'new_test1': {}, 'new_test2': {} } } ''' return __salt__['net.load_template']('schedule_probes', probes=probes, test=test, commit=commit, inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
saltstack/salt
salt/returners/couchbase_return.py
_get_connection
python
def _get_connection(): ''' Global function to access the couchbase connection (and make it if its closed) ''' global COUCHBASE_CONN if COUCHBASE_CONN is None: opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket']) return COUCHBASE_CONN
Global function to access the couchbase connection (and make it if its closed)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L106-L123
null
# -*- coding: utf-8 -*- ''' Simple returner for Couchbase. Optional configuration settings are listed below, along with sane defaults. .. code-block:: yaml couchbase.host: 'salt' couchbase.port: 8091 couchbase.bucket: 'salt' couchbase.ttl: 24 couchbase.password: 'password' couchbase.skip_verify_views: False To use the couchbase returner, append '--return couchbase' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return couchbase To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_kwargs '{"bucket": "another-salt"}' All of the return data will be stored in documents as follows: JID === load: load obj tgt_minions: list of minions targeted nocache: should we not cache the return data JID/MINION_ID ============= return: return_data full_ret: full load of job return ''' from __future__ import absolute_import, print_function, unicode_literals import logging try: import couchbase HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.jid import salt.utils.json import salt.utils.minions # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchbase' # some globals COUCHBASE_CONN = None DESIGN_NAME = 'couchbase_returner' VERIFIED_VIEWS = False _json = salt.utils.json.import_json() def _json_dumps(obj, **kwargs): return salt.utils.json.dumps(obj, _json_module=_json) def __virtual__(): if not HAS_DEPS: return False, 'Could not import couchbase returner; couchbase is not installed.' couchbase.set_json_converters(_json_dumps, salt.utils.json.loads) return __virtualname__ def _get_options(): ''' Get the couchbase options from salt. Apply defaults if required. ''' return {'host': __opts__.get('couchbase.host', 'salt'), 'port': __opts__.get('couchbase.port', 8091), 'bucket': __opts__.get('couchbase.bucket', 'salt'), 'password': __opts__.get('couchbase.password', '')} def _verify_views(): ''' Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config ''' global VERIFIED_VIEWS if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False): return cb_ = _get_connection() ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"}, 'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"} } } try: curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value if curr_ddoc['views'] == ddoc['views']: VERIFIED_VIEWS = True return except couchbase.exceptions.HTTPError: pass cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False) VERIFIED_VIEWS = True def _get_ttl(): ''' Return the TTL that we should store our objects with ''' return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours #TODO: add to returner docs-- this is a new one def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case ''' if passed_jid is None: jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid cb_ = _get_connection() try: cb_.add(six.text_type(jid), {'nocache': nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice if passed_jid is None: return prep_jid(nocache=nocache) return jid def returner(load): ''' Return data to couchbase bucket ''' cb_ = _get_connection() hn_key = '{0}/{1}'.format(load['jid'], load['id']) try: ret_doc = {'return': load['return'], 'full_ret': salt.utils.json.dumps(load)} cb_.add(hn_key, ret_doc, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.text_type(jid)) jid_doc.value['load'] = clear_load cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] save_minions(jid, minions) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only. ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: log.warning('Could not write job cache file for jid: %s', jid) return False # save the minions to a cache so we can see in the UI if 'minions' in jid_doc.value: jid_doc.value['minions'] = sorted( set(jid_doc.value['minions'] + minions) ) else: jid_doc.value['minions'] = minions cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) def get_load(jid): ''' Return the load data that marks a specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value['load'] ret['Minions'] = jid_doc.value['minions'] except KeyError as e: log.error(e) return ret def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jid_returns', key=six.text_type(jid), include_docs=True): ret[result.value] = result.doc.value return ret def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret def _format_job_instance(job): ''' Return a properly formatted job dict ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
saltstack/salt
salt/returners/couchbase_return.py
_verify_views
python
def _verify_views(): ''' Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config ''' global VERIFIED_VIEWS if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False): return cb_ = _get_connection() ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"}, 'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"} } } try: curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value if curr_ddoc['views'] == ddoc['views']: VERIFIED_VIEWS = True return except couchbase.exceptions.HTTPError: pass cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False) VERIFIED_VIEWS = True
Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L126-L150
null
# -*- coding: utf-8 -*- ''' Simple returner for Couchbase. Optional configuration settings are listed below, along with sane defaults. .. code-block:: yaml couchbase.host: 'salt' couchbase.port: 8091 couchbase.bucket: 'salt' couchbase.ttl: 24 couchbase.password: 'password' couchbase.skip_verify_views: False To use the couchbase returner, append '--return couchbase' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return couchbase To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_kwargs '{"bucket": "another-salt"}' All of the return data will be stored in documents as follows: JID === load: load obj tgt_minions: list of minions targeted nocache: should we not cache the return data JID/MINION_ID ============= return: return_data full_ret: full load of job return ''' from __future__ import absolute_import, print_function, unicode_literals import logging try: import couchbase HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.jid import salt.utils.json import salt.utils.minions # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchbase' # some globals COUCHBASE_CONN = None DESIGN_NAME = 'couchbase_returner' VERIFIED_VIEWS = False _json = salt.utils.json.import_json() def _json_dumps(obj, **kwargs): return salt.utils.json.dumps(obj, _json_module=_json) def __virtual__(): if not HAS_DEPS: return False, 'Could not import couchbase returner; couchbase is not installed.' couchbase.set_json_converters(_json_dumps, salt.utils.json.loads) return __virtualname__ def _get_options(): ''' Get the couchbase options from salt. Apply defaults if required. ''' return {'host': __opts__.get('couchbase.host', 'salt'), 'port': __opts__.get('couchbase.port', 8091), 'bucket': __opts__.get('couchbase.bucket', 'salt'), 'password': __opts__.get('couchbase.password', '')} def _get_connection(): ''' Global function to access the couchbase connection (and make it if its closed) ''' global COUCHBASE_CONN if COUCHBASE_CONN is None: opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket']) return COUCHBASE_CONN def _get_ttl(): ''' Return the TTL that we should store our objects with ''' return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours #TODO: add to returner docs-- this is a new one def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case ''' if passed_jid is None: jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid cb_ = _get_connection() try: cb_.add(six.text_type(jid), {'nocache': nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice if passed_jid is None: return prep_jid(nocache=nocache) return jid def returner(load): ''' Return data to couchbase bucket ''' cb_ = _get_connection() hn_key = '{0}/{1}'.format(load['jid'], load['id']) try: ret_doc = {'return': load['return'], 'full_ret': salt.utils.json.dumps(load)} cb_.add(hn_key, ret_doc, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.text_type(jid)) jid_doc.value['load'] = clear_load cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] save_minions(jid, minions) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only. ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: log.warning('Could not write job cache file for jid: %s', jid) return False # save the minions to a cache so we can see in the UI if 'minions' in jid_doc.value: jid_doc.value['minions'] = sorted( set(jid_doc.value['minions'] + minions) ) else: jid_doc.value['minions'] = minions cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) def get_load(jid): ''' Return the load data that marks a specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value['load'] ret['Minions'] = jid_doc.value['minions'] except KeyError as e: log.error(e) return ret def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jid_returns', key=six.text_type(jid), include_docs=True): ret[result.value] = result.doc.value return ret def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret def _format_job_instance(job): ''' Return a properly formatted job dict ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
saltstack/salt
salt/returners/couchbase_return.py
prep_jid
python
def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case ''' if passed_jid is None: jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid cb_ = _get_connection() try: cb_.add(six.text_type(jid), {'nocache': nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice if passed_jid is None: return prep_jid(nocache=nocache) return jid
Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L161-L185
[ "def gen_jid(opts=None):\n '''\n Generate a jid\n '''\n if opts is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). '\n 'This will be required starting in {version}.'\n )\n opts = {}\n global LAST_JID_DATETIME # pylint: disable=global-statement\n\n if opts.get('utc_jid', False):\n jid_dt = datetime.datetime.utcnow()\n else:\n jid_dt = datetime.datetime.now()\n if not opts.get('unique_jid', False):\n return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt)\n if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt:\n jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1)\n LAST_JID_DATETIME = jid_dt\n return '{0:%Y%m%d%H%M%S%f}_{1}'.format(jid_dt, os.getpid())\n", "def prep_jid(nocache=False, passed_jid=None):\n '''\n Return a job id and prepare the job id directory\n This is the function responsible for making sure jids don't collide (unless\n its passed a jid)\n So do what you have to do to make sure that stays the case\n '''\n if passed_jid is None:\n jid = salt.utils.jid.gen_jid(__opts__)\n else:\n jid = passed_jid\n\n cb_ = _get_connection()\n\n try:\n cb_.add(six.text_type(jid),\n {'nocache': nocache},\n ttl=_get_ttl(),\n )\n except couchbase.exceptions.KeyExistsError:\n # TODO: some sort of sleep or something? Spinning is generally bad practice\n if passed_jid is None:\n return prep_jid(nocache=nocache)\n\n return jid\n", "def _get_connection():\n '''\n Global function to access the couchbase connection (and make it if its closed)\n '''\n global COUCHBASE_CONN\n if COUCHBASE_CONN is None:\n opts = _get_options()\n if opts['password']:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'],\n password=opts['password'])\n else:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'])\n\n return COUCHBASE_CONN\n", "def _get_ttl():\n '''\n Return the TTL that we should store our objects with\n '''\n return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for Couchbase. Optional configuration settings are listed below, along with sane defaults. .. code-block:: yaml couchbase.host: 'salt' couchbase.port: 8091 couchbase.bucket: 'salt' couchbase.ttl: 24 couchbase.password: 'password' couchbase.skip_verify_views: False To use the couchbase returner, append '--return couchbase' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return couchbase To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_kwargs '{"bucket": "another-salt"}' All of the return data will be stored in documents as follows: JID === load: load obj tgt_minions: list of minions targeted nocache: should we not cache the return data JID/MINION_ID ============= return: return_data full_ret: full load of job return ''' from __future__ import absolute_import, print_function, unicode_literals import logging try: import couchbase HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.jid import salt.utils.json import salt.utils.minions # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchbase' # some globals COUCHBASE_CONN = None DESIGN_NAME = 'couchbase_returner' VERIFIED_VIEWS = False _json = salt.utils.json.import_json() def _json_dumps(obj, **kwargs): return salt.utils.json.dumps(obj, _json_module=_json) def __virtual__(): if not HAS_DEPS: return False, 'Could not import couchbase returner; couchbase is not installed.' couchbase.set_json_converters(_json_dumps, salt.utils.json.loads) return __virtualname__ def _get_options(): ''' Get the couchbase options from salt. Apply defaults if required. ''' return {'host': __opts__.get('couchbase.host', 'salt'), 'port': __opts__.get('couchbase.port', 8091), 'bucket': __opts__.get('couchbase.bucket', 'salt'), 'password': __opts__.get('couchbase.password', '')} def _get_connection(): ''' Global function to access the couchbase connection (and make it if its closed) ''' global COUCHBASE_CONN if COUCHBASE_CONN is None: opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket']) return COUCHBASE_CONN def _verify_views(): ''' Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config ''' global VERIFIED_VIEWS if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False): return cb_ = _get_connection() ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"}, 'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"} } } try: curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value if curr_ddoc['views'] == ddoc['views']: VERIFIED_VIEWS = True return except couchbase.exceptions.HTTPError: pass cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False) VERIFIED_VIEWS = True def _get_ttl(): ''' Return the TTL that we should store our objects with ''' return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours #TODO: add to returner docs-- this is a new one def returner(load): ''' Return data to couchbase bucket ''' cb_ = _get_connection() hn_key = '{0}/{1}'.format(load['jid'], load['id']) try: ret_doc = {'return': load['return'], 'full_ret': salt.utils.json.dumps(load)} cb_.add(hn_key, ret_doc, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.text_type(jid)) jid_doc.value['load'] = clear_load cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] save_minions(jid, minions) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only. ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: log.warning('Could not write job cache file for jid: %s', jid) return False # save the minions to a cache so we can see in the UI if 'minions' in jid_doc.value: jid_doc.value['minions'] = sorted( set(jid_doc.value['minions'] + minions) ) else: jid_doc.value['minions'] = minions cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) def get_load(jid): ''' Return the load data that marks a specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value['load'] ret['Minions'] = jid_doc.value['minions'] except KeyError as e: log.error(e) return ret def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jid_returns', key=six.text_type(jid), include_docs=True): ret[result.value] = result.doc.value return ret def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret def _format_job_instance(job): ''' Return a properly formatted job dict ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
saltstack/salt
salt/returners/couchbase_return.py
returner
python
def returner(load): ''' Return data to couchbase bucket ''' cb_ = _get_connection() hn_key = '{0}/{1}'.format(load['jid'], load['id']) try: ret_doc = {'return': load['return'], 'full_ret': salt.utils.json.dumps(load)} cb_.add(hn_key, ret_doc, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False
Return data to couchbase bucket
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L188-L208
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_connection():\n '''\n Global function to access the couchbase connection (and make it if its closed)\n '''\n global COUCHBASE_CONN\n if COUCHBASE_CONN is None:\n opts = _get_options()\n if opts['password']:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'],\n password=opts['password'])\n else:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'])\n\n return COUCHBASE_CONN\n", "def _get_ttl():\n '''\n Return the TTL that we should store our objects with\n '''\n return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for Couchbase. Optional configuration settings are listed below, along with sane defaults. .. code-block:: yaml couchbase.host: 'salt' couchbase.port: 8091 couchbase.bucket: 'salt' couchbase.ttl: 24 couchbase.password: 'password' couchbase.skip_verify_views: False To use the couchbase returner, append '--return couchbase' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return couchbase To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_kwargs '{"bucket": "another-salt"}' All of the return data will be stored in documents as follows: JID === load: load obj tgt_minions: list of minions targeted nocache: should we not cache the return data JID/MINION_ID ============= return: return_data full_ret: full load of job return ''' from __future__ import absolute_import, print_function, unicode_literals import logging try: import couchbase HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.jid import salt.utils.json import salt.utils.minions # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchbase' # some globals COUCHBASE_CONN = None DESIGN_NAME = 'couchbase_returner' VERIFIED_VIEWS = False _json = salt.utils.json.import_json() def _json_dumps(obj, **kwargs): return salt.utils.json.dumps(obj, _json_module=_json) def __virtual__(): if not HAS_DEPS: return False, 'Could not import couchbase returner; couchbase is not installed.' couchbase.set_json_converters(_json_dumps, salt.utils.json.loads) return __virtualname__ def _get_options(): ''' Get the couchbase options from salt. Apply defaults if required. ''' return {'host': __opts__.get('couchbase.host', 'salt'), 'port': __opts__.get('couchbase.port', 8091), 'bucket': __opts__.get('couchbase.bucket', 'salt'), 'password': __opts__.get('couchbase.password', '')} def _get_connection(): ''' Global function to access the couchbase connection (and make it if its closed) ''' global COUCHBASE_CONN if COUCHBASE_CONN is None: opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket']) return COUCHBASE_CONN def _verify_views(): ''' Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config ''' global VERIFIED_VIEWS if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False): return cb_ = _get_connection() ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"}, 'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"} } } try: curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value if curr_ddoc['views'] == ddoc['views']: VERIFIED_VIEWS = True return except couchbase.exceptions.HTTPError: pass cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False) VERIFIED_VIEWS = True def _get_ttl(): ''' Return the TTL that we should store our objects with ''' return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours #TODO: add to returner docs-- this is a new one def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case ''' if passed_jid is None: jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid cb_ = _get_connection() try: cb_.add(six.text_type(jid), {'nocache': nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice if passed_jid is None: return prep_jid(nocache=nocache) return jid def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.text_type(jid)) jid_doc.value['load'] = clear_load cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] save_minions(jid, minions) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only. ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: log.warning('Could not write job cache file for jid: %s', jid) return False # save the minions to a cache so we can see in the UI if 'minions' in jid_doc.value: jid_doc.value['minions'] = sorted( set(jid_doc.value['minions'] + minions) ) else: jid_doc.value['minions'] = minions cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) def get_load(jid): ''' Return the load data that marks a specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value['load'] ret['Minions'] = jid_doc.value['minions'] except KeyError as e: log.error(e) return ret def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jid_returns', key=six.text_type(jid), include_docs=True): ret[result.value] = result.doc.value return ret def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret def _format_job_instance(job): ''' Return a properly formatted job dict ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
saltstack/salt
salt/returners/couchbase_return.py
save_load
python
def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.text_type(jid)) jid_doc.value['load'] = clear_load cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] save_minions(jid, minions)
Save the load to the specified jid
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L211-L235
[ "def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument\n '''\n Save/update the minion list for a given jid. The syndic_id argument is\n included for API compatibility only.\n '''\n cb_ = _get_connection()\n\n try:\n jid_doc = cb_.get(six.text_type(jid))\n except couchbase.exceptions.NotFoundError:\n log.warning('Could not write job cache file for jid: %s', jid)\n return False\n\n # save the minions to a cache so we can see in the UI\n if 'minions' in jid_doc.value:\n jid_doc.value['minions'] = sorted(\n set(jid_doc.value['minions'] + minions)\n )\n else:\n jid_doc.value['minions'] = minions\n cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl())\n", "def _get_connection():\n '''\n Global function to access the couchbase connection (and make it if its closed)\n '''\n global COUCHBASE_CONN\n if COUCHBASE_CONN is None:\n opts = _get_options()\n if opts['password']:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'],\n password=opts['password'])\n else:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'])\n\n return COUCHBASE_CONN\n", "def _get_ttl():\n '''\n Return the TTL that we should store our objects with\n '''\n return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours\n", "def check_minions(self,\n expr,\n tgt_type='glob',\n delimiter=DEFAULT_TARGET_DELIM,\n greedy=True):\n '''\n Check the passed regex against the available minions' public keys\n stored for authentication. This should return a set of ids which\n match the regex, this will then be used to parse the returns to\n make sure everyone has checked back in.\n '''\n\n try:\n if expr is None:\n expr = ''\n check_func = getattr(self, '_check_{0}_minions'.format(tgt_type), None)\n if tgt_type in ('grain',\n 'grain_pcre',\n 'pillar',\n 'pillar_pcre',\n 'pillar_exact',\n 'compound',\n 'compound_pillar_exact'):\n _res = check_func(expr, delimiter, greedy)\n else:\n _res = check_func(expr, greedy)\n _res['ssh_minions'] = False\n if self.opts.get('enable_ssh_minions', False) is True and isinstance('tgt', six.string_types):\n roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))\n ssh_minions = roster.targets(expr, tgt_type)\n if ssh_minions:\n _res['minions'].extend(ssh_minions)\n _res['ssh_minions'] = True\n except Exception:\n log.exception(\n 'Failed matching available minions with %s pattern: %s',\n tgt_type, expr)\n _res = {'minions': [], 'missing': []}\n return _res\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for Couchbase. Optional configuration settings are listed below, along with sane defaults. .. code-block:: yaml couchbase.host: 'salt' couchbase.port: 8091 couchbase.bucket: 'salt' couchbase.ttl: 24 couchbase.password: 'password' couchbase.skip_verify_views: False To use the couchbase returner, append '--return couchbase' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return couchbase To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_kwargs '{"bucket": "another-salt"}' All of the return data will be stored in documents as follows: JID === load: load obj tgt_minions: list of minions targeted nocache: should we not cache the return data JID/MINION_ID ============= return: return_data full_ret: full load of job return ''' from __future__ import absolute_import, print_function, unicode_literals import logging try: import couchbase HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.jid import salt.utils.json import salt.utils.minions # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchbase' # some globals COUCHBASE_CONN = None DESIGN_NAME = 'couchbase_returner' VERIFIED_VIEWS = False _json = salt.utils.json.import_json() def _json_dumps(obj, **kwargs): return salt.utils.json.dumps(obj, _json_module=_json) def __virtual__(): if not HAS_DEPS: return False, 'Could not import couchbase returner; couchbase is not installed.' couchbase.set_json_converters(_json_dumps, salt.utils.json.loads) return __virtualname__ def _get_options(): ''' Get the couchbase options from salt. Apply defaults if required. ''' return {'host': __opts__.get('couchbase.host', 'salt'), 'port': __opts__.get('couchbase.port', 8091), 'bucket': __opts__.get('couchbase.bucket', 'salt'), 'password': __opts__.get('couchbase.password', '')} def _get_connection(): ''' Global function to access the couchbase connection (and make it if its closed) ''' global COUCHBASE_CONN if COUCHBASE_CONN is None: opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket']) return COUCHBASE_CONN def _verify_views(): ''' Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config ''' global VERIFIED_VIEWS if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False): return cb_ = _get_connection() ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"}, 'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"} } } try: curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value if curr_ddoc['views'] == ddoc['views']: VERIFIED_VIEWS = True return except couchbase.exceptions.HTTPError: pass cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False) VERIFIED_VIEWS = True def _get_ttl(): ''' Return the TTL that we should store our objects with ''' return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours #TODO: add to returner docs-- this is a new one def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case ''' if passed_jid is None: jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid cb_ = _get_connection() try: cb_.add(six.text_type(jid), {'nocache': nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice if passed_jid is None: return prep_jid(nocache=nocache) return jid def returner(load): ''' Return data to couchbase bucket ''' cb_ = _get_connection() hn_key = '{0}/{1}'.format(load['jid'], load['id']) try: ret_doc = {'return': load['return'], 'full_ret': salt.utils.json.dumps(load)} cb_.add(hn_key, ret_doc, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only. ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: log.warning('Could not write job cache file for jid: %s', jid) return False # save the minions to a cache so we can see in the UI if 'minions' in jid_doc.value: jid_doc.value['minions'] = sorted( set(jid_doc.value['minions'] + minions) ) else: jid_doc.value['minions'] = minions cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) def get_load(jid): ''' Return the load data that marks a specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value['load'] ret['Minions'] = jid_doc.value['minions'] except KeyError as e: log.error(e) return ret def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jid_returns', key=six.text_type(jid), include_docs=True): ret[result.value] = result.doc.value return ret def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret def _format_job_instance(job): ''' Return a properly formatted job dict ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
saltstack/salt
salt/returners/couchbase_return.py
save_minions
python
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only. ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: log.warning('Could not write job cache file for jid: %s', jid) return False # save the minions to a cache so we can see in the UI if 'minions' in jid_doc.value: jid_doc.value['minions'] = sorted( set(jid_doc.value['minions'] + minions) ) else: jid_doc.value['minions'] = minions cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl())
Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L238-L258
[ "def _get_connection():\n '''\n Global function to access the couchbase connection (and make it if its closed)\n '''\n global COUCHBASE_CONN\n if COUCHBASE_CONN is None:\n opts = _get_options()\n if opts['password']:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'],\n password=opts['password'])\n else:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'])\n\n return COUCHBASE_CONN\n", "def _get_ttl():\n '''\n Return the TTL that we should store our objects with\n '''\n return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for Couchbase. Optional configuration settings are listed below, along with sane defaults. .. code-block:: yaml couchbase.host: 'salt' couchbase.port: 8091 couchbase.bucket: 'salt' couchbase.ttl: 24 couchbase.password: 'password' couchbase.skip_verify_views: False To use the couchbase returner, append '--return couchbase' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return couchbase To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_kwargs '{"bucket": "another-salt"}' All of the return data will be stored in documents as follows: JID === load: load obj tgt_minions: list of minions targeted nocache: should we not cache the return data JID/MINION_ID ============= return: return_data full_ret: full load of job return ''' from __future__ import absolute_import, print_function, unicode_literals import logging try: import couchbase HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.jid import salt.utils.json import salt.utils.minions # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchbase' # some globals COUCHBASE_CONN = None DESIGN_NAME = 'couchbase_returner' VERIFIED_VIEWS = False _json = salt.utils.json.import_json() def _json_dumps(obj, **kwargs): return salt.utils.json.dumps(obj, _json_module=_json) def __virtual__(): if not HAS_DEPS: return False, 'Could not import couchbase returner; couchbase is not installed.' couchbase.set_json_converters(_json_dumps, salt.utils.json.loads) return __virtualname__ def _get_options(): ''' Get the couchbase options from salt. Apply defaults if required. ''' return {'host': __opts__.get('couchbase.host', 'salt'), 'port': __opts__.get('couchbase.port', 8091), 'bucket': __opts__.get('couchbase.bucket', 'salt'), 'password': __opts__.get('couchbase.password', '')} def _get_connection(): ''' Global function to access the couchbase connection (and make it if its closed) ''' global COUCHBASE_CONN if COUCHBASE_CONN is None: opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket']) return COUCHBASE_CONN def _verify_views(): ''' Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config ''' global VERIFIED_VIEWS if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False): return cb_ = _get_connection() ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"}, 'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"} } } try: curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value if curr_ddoc['views'] == ddoc['views']: VERIFIED_VIEWS = True return except couchbase.exceptions.HTTPError: pass cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False) VERIFIED_VIEWS = True def _get_ttl(): ''' Return the TTL that we should store our objects with ''' return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours #TODO: add to returner docs-- this is a new one def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case ''' if passed_jid is None: jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid cb_ = _get_connection() try: cb_.add(six.text_type(jid), {'nocache': nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice if passed_jid is None: return prep_jid(nocache=nocache) return jid def returner(load): ''' Return data to couchbase bucket ''' cb_ = _get_connection() hn_key = '{0}/{1}'.format(load['jid'], load['id']) try: ret_doc = {'return': load['return'], 'full_ret': salt.utils.json.dumps(load)} cb_.add(hn_key, ret_doc, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.text_type(jid)) jid_doc.value['load'] = clear_load cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] save_minions(jid, minions) def get_load(jid): ''' Return the load data that marks a specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value['load'] ret['Minions'] = jid_doc.value['minions'] except KeyError as e: log.error(e) return ret def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jid_returns', key=six.text_type(jid), include_docs=True): ret[result.value] = result.doc.value return ret def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret def _format_job_instance(job): ''' Return a properly formatted job dict ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
saltstack/salt
salt/returners/couchbase_return.py
get_load
python
def get_load(jid): ''' Return the load data that marks a specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value['load'] ret['Minions'] = jid_doc.value['minions'] except KeyError as e: log.error(e) return ret
Return the load data that marks a specified jid
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L261-L279
[ "def _get_connection():\n '''\n Global function to access the couchbase connection (and make it if its closed)\n '''\n global COUCHBASE_CONN\n if COUCHBASE_CONN is None:\n opts = _get_options()\n if opts['password']:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'],\n password=opts['password'])\n else:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'])\n\n return COUCHBASE_CONN\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for Couchbase. Optional configuration settings are listed below, along with sane defaults. .. code-block:: yaml couchbase.host: 'salt' couchbase.port: 8091 couchbase.bucket: 'salt' couchbase.ttl: 24 couchbase.password: 'password' couchbase.skip_verify_views: False To use the couchbase returner, append '--return couchbase' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return couchbase To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_kwargs '{"bucket": "another-salt"}' All of the return data will be stored in documents as follows: JID === load: load obj tgt_minions: list of minions targeted nocache: should we not cache the return data JID/MINION_ID ============= return: return_data full_ret: full load of job return ''' from __future__ import absolute_import, print_function, unicode_literals import logging try: import couchbase HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.jid import salt.utils.json import salt.utils.minions # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchbase' # some globals COUCHBASE_CONN = None DESIGN_NAME = 'couchbase_returner' VERIFIED_VIEWS = False _json = salt.utils.json.import_json() def _json_dumps(obj, **kwargs): return salt.utils.json.dumps(obj, _json_module=_json) def __virtual__(): if not HAS_DEPS: return False, 'Could not import couchbase returner; couchbase is not installed.' couchbase.set_json_converters(_json_dumps, salt.utils.json.loads) return __virtualname__ def _get_options(): ''' Get the couchbase options from salt. Apply defaults if required. ''' return {'host': __opts__.get('couchbase.host', 'salt'), 'port': __opts__.get('couchbase.port', 8091), 'bucket': __opts__.get('couchbase.bucket', 'salt'), 'password': __opts__.get('couchbase.password', '')} def _get_connection(): ''' Global function to access the couchbase connection (and make it if its closed) ''' global COUCHBASE_CONN if COUCHBASE_CONN is None: opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket']) return COUCHBASE_CONN def _verify_views(): ''' Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config ''' global VERIFIED_VIEWS if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False): return cb_ = _get_connection() ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"}, 'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"} } } try: curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value if curr_ddoc['views'] == ddoc['views']: VERIFIED_VIEWS = True return except couchbase.exceptions.HTTPError: pass cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False) VERIFIED_VIEWS = True def _get_ttl(): ''' Return the TTL that we should store our objects with ''' return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours #TODO: add to returner docs-- this is a new one def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case ''' if passed_jid is None: jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid cb_ = _get_connection() try: cb_.add(six.text_type(jid), {'nocache': nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice if passed_jid is None: return prep_jid(nocache=nocache) return jid def returner(load): ''' Return data to couchbase bucket ''' cb_ = _get_connection() hn_key = '{0}/{1}'.format(load['jid'], load['id']) try: ret_doc = {'return': load['return'], 'full_ret': salt.utils.json.dumps(load)} cb_.add(hn_key, ret_doc, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.text_type(jid)) jid_doc.value['load'] = clear_load cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] save_minions(jid, minions) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only. ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: log.warning('Could not write job cache file for jid: %s', jid) return False # save the minions to a cache so we can see in the UI if 'minions' in jid_doc.value: jid_doc.value['minions'] = sorted( set(jid_doc.value['minions'] + minions) ) else: jid_doc.value['minions'] = minions cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jid_returns', key=six.text_type(jid), include_docs=True): ret[result.value] = result.doc.value return ret def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret def _format_job_instance(job): ''' Return a properly formatted job dict ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
saltstack/salt
salt/returners/couchbase_return.py
get_jid
python
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jid_returns', key=six.text_type(jid), include_docs=True): ret[result.value] = result.doc.value return ret
Return the information returned when the specified job id was executed
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L282-L294
[ "def _get_connection():\n '''\n Global function to access the couchbase connection (and make it if its closed)\n '''\n global COUCHBASE_CONN\n if COUCHBASE_CONN is None:\n opts = _get_options()\n if opts['password']:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'],\n password=opts['password'])\n else:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'])\n\n return COUCHBASE_CONN\n", "def _verify_views():\n '''\n Verify that you have the views you need. This can be disabled by\n adding couchbase.skip_verify_views: True in config\n '''\n global VERIFIED_VIEWS\n\n if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False):\n return\n cb_ = _get_connection()\n ddoc = {'views': {'jids': {'map': \"function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }\"},\n 'jid_returns': {'map': \"function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }\"}\n }\n }\n\n try:\n curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value\n if curr_ddoc['views'] == ddoc['views']:\n VERIFIED_VIEWS = True\n return\n except couchbase.exceptions.HTTPError:\n pass\n\n cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False)\n VERIFIED_VIEWS = True\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for Couchbase. Optional configuration settings are listed below, along with sane defaults. .. code-block:: yaml couchbase.host: 'salt' couchbase.port: 8091 couchbase.bucket: 'salt' couchbase.ttl: 24 couchbase.password: 'password' couchbase.skip_verify_views: False To use the couchbase returner, append '--return couchbase' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return couchbase To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_kwargs '{"bucket": "another-salt"}' All of the return data will be stored in documents as follows: JID === load: load obj tgt_minions: list of minions targeted nocache: should we not cache the return data JID/MINION_ID ============= return: return_data full_ret: full load of job return ''' from __future__ import absolute_import, print_function, unicode_literals import logging try: import couchbase HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.jid import salt.utils.json import salt.utils.minions # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchbase' # some globals COUCHBASE_CONN = None DESIGN_NAME = 'couchbase_returner' VERIFIED_VIEWS = False _json = salt.utils.json.import_json() def _json_dumps(obj, **kwargs): return salt.utils.json.dumps(obj, _json_module=_json) def __virtual__(): if not HAS_DEPS: return False, 'Could not import couchbase returner; couchbase is not installed.' couchbase.set_json_converters(_json_dumps, salt.utils.json.loads) return __virtualname__ def _get_options(): ''' Get the couchbase options from salt. Apply defaults if required. ''' return {'host': __opts__.get('couchbase.host', 'salt'), 'port': __opts__.get('couchbase.port', 8091), 'bucket': __opts__.get('couchbase.bucket', 'salt'), 'password': __opts__.get('couchbase.password', '')} def _get_connection(): ''' Global function to access the couchbase connection (and make it if its closed) ''' global COUCHBASE_CONN if COUCHBASE_CONN is None: opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket']) return COUCHBASE_CONN def _verify_views(): ''' Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config ''' global VERIFIED_VIEWS if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False): return cb_ = _get_connection() ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"}, 'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"} } } try: curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value if curr_ddoc['views'] == ddoc['views']: VERIFIED_VIEWS = True return except couchbase.exceptions.HTTPError: pass cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False) VERIFIED_VIEWS = True def _get_ttl(): ''' Return the TTL that we should store our objects with ''' return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours #TODO: add to returner docs-- this is a new one def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case ''' if passed_jid is None: jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid cb_ = _get_connection() try: cb_.add(six.text_type(jid), {'nocache': nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice if passed_jid is None: return prep_jid(nocache=nocache) return jid def returner(load): ''' Return data to couchbase bucket ''' cb_ = _get_connection() hn_key = '{0}/{1}'.format(load['jid'], load['id']) try: ret_doc = {'return': load['return'], 'full_ret': salt.utils.json.dumps(load)} cb_.add(hn_key, ret_doc, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.text_type(jid)) jid_doc.value['load'] = clear_load cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] save_minions(jid, minions) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only. ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: log.warning('Could not write job cache file for jid: %s', jid) return False # save the minions to a cache so we can see in the UI if 'minions' in jid_doc.value: jid_doc.value['minions'] = sorted( set(jid_doc.value['minions'] + minions) ) else: jid_doc.value['minions'] = minions cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) def get_load(jid): ''' Return the load data that marks a specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value['load'] ret['Minions'] = jid_doc.value['minions'] except KeyError as e: log.error(e) return ret def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret def _format_job_instance(job): ''' Return a properly formatted job dict ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
saltstack/salt
salt/returners/couchbase_return.py
get_jids
python
def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret
Return a list of all job ids
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L297-L309
[ "def _get_connection():\n '''\n Global function to access the couchbase connection (and make it if its closed)\n '''\n global COUCHBASE_CONN\n if COUCHBASE_CONN is None:\n opts = _get_options()\n if opts['password']:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'],\n password=opts['password'])\n else:\n COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'],\n port=opts['port'],\n bucket=opts['bucket'])\n\n return COUCHBASE_CONN\n", "def _verify_views():\n '''\n Verify that you have the views you need. This can be disabled by\n adding couchbase.skip_verify_views: True in config\n '''\n global VERIFIED_VIEWS\n\n if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False):\n return\n cb_ = _get_connection()\n ddoc = {'views': {'jids': {'map': \"function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }\"},\n 'jid_returns': {'map': \"function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }\"}\n }\n }\n\n try:\n curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value\n if curr_ddoc['views'] == ddoc['views']:\n VERIFIED_VIEWS = True\n return\n except couchbase.exceptions.HTTPError:\n pass\n\n cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False)\n VERIFIED_VIEWS = True\n", "def _format_jid_instance(jid, job):\n '''\n Return a properly formatted jid dict\n '''\n ret = _format_job_instance(job)\n ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for Couchbase. Optional configuration settings are listed below, along with sane defaults. .. code-block:: yaml couchbase.host: 'salt' couchbase.port: 8091 couchbase.bucket: 'salt' couchbase.ttl: 24 couchbase.password: 'password' couchbase.skip_verify_views: False To use the couchbase returner, append '--return couchbase' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return couchbase To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_kwargs '{"bucket": "another-salt"}' All of the return data will be stored in documents as follows: JID === load: load obj tgt_minions: list of minions targeted nocache: should we not cache the return data JID/MINION_ID ============= return: return_data full_ret: full load of job return ''' from __future__ import absolute_import, print_function, unicode_literals import logging try: import couchbase HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.jid import salt.utils.json import salt.utils.minions # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchbase' # some globals COUCHBASE_CONN = None DESIGN_NAME = 'couchbase_returner' VERIFIED_VIEWS = False _json = salt.utils.json.import_json() def _json_dumps(obj, **kwargs): return salt.utils.json.dumps(obj, _json_module=_json) def __virtual__(): if not HAS_DEPS: return False, 'Could not import couchbase returner; couchbase is not installed.' couchbase.set_json_converters(_json_dumps, salt.utils.json.loads) return __virtualname__ def _get_options(): ''' Get the couchbase options from salt. Apply defaults if required. ''' return {'host': __opts__.get('couchbase.host', 'salt'), 'port': __opts__.get('couchbase.port', 8091), 'bucket': __opts__.get('couchbase.bucket', 'salt'), 'password': __opts__.get('couchbase.password', '')} def _get_connection(): ''' Global function to access the couchbase connection (and make it if its closed) ''' global COUCHBASE_CONN if COUCHBASE_CONN is None: opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket']) return COUCHBASE_CONN def _verify_views(): ''' Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config ''' global VERIFIED_VIEWS if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False): return cb_ = _get_connection() ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"}, 'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"} } } try: curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value if curr_ddoc['views'] == ddoc['views']: VERIFIED_VIEWS = True return except couchbase.exceptions.HTTPError: pass cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False) VERIFIED_VIEWS = True def _get_ttl(): ''' Return the TTL that we should store our objects with ''' return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours #TODO: add to returner docs-- this is a new one def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case ''' if passed_jid is None: jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid cb_ = _get_connection() try: cb_.add(six.text_type(jid), {'nocache': nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice if passed_jid is None: return prep_jid(nocache=nocache) return jid def returner(load): ''' Return data to couchbase bucket ''' cb_ = _get_connection() hn_key = '{0}/{1}'.format(load['jid'], load['id']) try: ret_doc = {'return': load['return'], 'full_ret': salt.utils.json.dumps(load)} cb_.add(hn_key, ret_doc, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.text_type(jid)) jid_doc.value['load'] = clear_load cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] save_minions(jid, minions) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only. ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: log.warning('Could not write job cache file for jid: %s', jid) return False # save the minions to a cache so we can see in the UI if 'minions' in jid_doc.value: jid_doc.value['minions'] = sorted( set(jid_doc.value['minions'] + minions) ) else: jid_doc.value['minions'] = minions cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) def get_load(jid): ''' Return the load data that marks a specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value['load'] ret['Minions'] = jid_doc.value['minions'] except KeyError as e: log.error(e) return ret def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jid_returns', key=six.text_type(jid), include_docs=True): ret[result.value] = result.doc.value return ret def _format_job_instance(job): ''' Return a properly formatted job dict ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
saltstack/salt
salt/returners/couchbase_return.py
_format_jid_instance
python
def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
Return a properly formatted jid dict
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L332-L338
[ "def _format_job_instance(job):\n '''\n Return a properly formatted job dict\n '''\n ret = {'Function': job.get('fun', 'unknown-function'),\n 'Arguments': list(job.get('arg', [])),\n # unlikely but safeguard from invalid returns\n 'Target': job.get('tgt', 'unknown-target'),\n 'Target-type': job.get('tgt_type', 'list'),\n 'User': job.get('user', 'root')}\n\n if 'metadata' in job:\n ret['Metadata'] = job.get('metadata', {})\n else:\n if 'kwargs' in job:\n if 'metadata' in job['kwargs']:\n ret['Metadata'] = job['kwargs'].get('metadata', {})\n return ret\n", "def jid_to_time(jid):\n '''\n Convert a salt job id into the time when the job was invoked\n '''\n jid = six.text_type(jid)\n if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'):\n return ''\n year = jid[:4]\n month = jid[4:6]\n day = jid[6:8]\n hour = jid[8:10]\n minute = jid[10:12]\n second = jid[12:14]\n micro = jid[14:20]\n\n ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year,\n months[int(month)],\n day,\n hour,\n minute,\n second,\n micro)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for Couchbase. Optional configuration settings are listed below, along with sane defaults. .. code-block:: yaml couchbase.host: 'salt' couchbase.port: 8091 couchbase.bucket: 'salt' couchbase.ttl: 24 couchbase.password: 'password' couchbase.skip_verify_views: False To use the couchbase returner, append '--return couchbase' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return couchbase To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchbase --return_kwargs '{"bucket": "another-salt"}' All of the return data will be stored in documents as follows: JID === load: load obj tgt_minions: list of minions targeted nocache: should we not cache the return data JID/MINION_ID ============= return: return_data full_ret: full load of job return ''' from __future__ import absolute_import, print_function, unicode_literals import logging try: import couchbase HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.jid import salt.utils.json import salt.utils.minions # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchbase' # some globals COUCHBASE_CONN = None DESIGN_NAME = 'couchbase_returner' VERIFIED_VIEWS = False _json = salt.utils.json.import_json() def _json_dumps(obj, **kwargs): return salt.utils.json.dumps(obj, _json_module=_json) def __virtual__(): if not HAS_DEPS: return False, 'Could not import couchbase returner; couchbase is not installed.' couchbase.set_json_converters(_json_dumps, salt.utils.json.loads) return __virtualname__ def _get_options(): ''' Get the couchbase options from salt. Apply defaults if required. ''' return {'host': __opts__.get('couchbase.host', 'salt'), 'port': __opts__.get('couchbase.port', 8091), 'bucket': __opts__.get('couchbase.bucket', 'salt'), 'password': __opts__.get('couchbase.password', '')} def _get_connection(): ''' Global function to access the couchbase connection (and make it if its closed) ''' global COUCHBASE_CONN if COUCHBASE_CONN is None: opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket']) return COUCHBASE_CONN def _verify_views(): ''' Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config ''' global VERIFIED_VIEWS if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False): return cb_ = _get_connection() ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"}, 'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"} } } try: curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value if curr_ddoc['views'] == ddoc['views']: VERIFIED_VIEWS = True return except couchbase.exceptions.HTTPError: pass cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False) VERIFIED_VIEWS = True def _get_ttl(): ''' Return the TTL that we should store our objects with ''' return __opts__.get('couchbase.ttl', 24) * 60 * 60 # keep_jobs is in hours #TODO: add to returner docs-- this is a new one def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case ''' if passed_jid is None: jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid cb_ = _get_connection() try: cb_.add(six.text_type(jid), {'nocache': nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice if passed_jid is None: return prep_jid(nocache=nocache) return jid def returner(load): ''' Return data to couchbase bucket ''' cb_ = _get_connection() hn_key = '{0}/{1}'.format(load['jid'], load['id']) try: ret_doc = {'return': load['return'], 'full_ret': salt.utils.json.dumps(load)} cb_.add(hn_key, ret_doc, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.text_type(jid)) jid_doc.value['load'] = clear_load cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] save_minions(jid, minions) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only. ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: log.warning('Could not write job cache file for jid: %s', jid) return False # save the minions to a cache so we can see in the UI if 'minions' in jid_doc.value: jid_doc.value['minions'] = sorted( set(jid_doc.value['minions'] + minions) ) else: jid_doc.value['minions'] = minions cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) def get_load(jid): ''' Return the load data that marks a specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value['load'] ret['Minions'] = jid_doc.value['minions'] except KeyError as e: log.error(e) return ret def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jid_returns', key=six.text_type(jid), include_docs=True): ret[result.value] = result.doc.value return ret def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret def _format_job_instance(job): ''' Return a properly formatted job dict ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret
saltstack/salt
salt/cache/redis_cache.py
_get_redis_cache_opts
python
def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), }
Return the Redis server connection details from the __opts__.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L205-L218
null
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) } def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank ) def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key ) def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank ) def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value) def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks) def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
saltstack/salt
salt/cache/redis_cache.py
_get_redis_server
python
def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER
Return the Redis server instance. Caching the object instance.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L221-L241
[ "def _get_redis_cache_opts():\n '''\n Return the Redis server connection details from the __opts__.\n '''\n return {\n 'host': __opts__.get('cache.redis.host', 'localhost'),\n 'port': __opts__.get('cache.redis.port', 6379),\n 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None),\n 'db': __opts__.get('cache.redis.db', '0'),\n 'password': __opts__.get('cache.redis.password', ''),\n 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False),\n 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}),\n 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False),\n }\n" ]
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), } def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) } def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank ) def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key ) def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank ) def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value) def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks) def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
saltstack/salt
salt/cache/redis_cache.py
_get_redis_keys_opts
python
def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) }
Build the key opts based on the user options.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L244-L253
null
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), } def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank ) def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key ) def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank ) def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value) def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks) def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
saltstack/salt
salt/cache/redis_cache.py
_get_bank_redis_key
python
def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank )
Return the Redis key for the bank given the name.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L256-L265
[ "def _get_redis_keys_opts():\n '''\n Build the key opts based on the user options.\n '''\n return {\n 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX),\n 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX),\n 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX),\n 'separator': __opts__.get('cache.redis.separator', _SEPARATOR)\n }\n" ]
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), } def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) } def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key ) def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank ) def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value) def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks) def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
saltstack/salt
salt/cache/redis_cache.py
_get_key_redis_key
python
def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key )
Return the Redis key given the bank name and the key name.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L268-L278
[ "def _get_redis_keys_opts():\n '''\n Build the key opts based on the user options.\n '''\n return {\n 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX),\n 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX),\n 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX),\n 'separator': __opts__.get('cache.redis.separator', _SEPARATOR)\n }\n" ]
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), } def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) } def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank ) def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank ) def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value) def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks) def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
saltstack/salt
salt/cache/redis_cache.py
_get_bank_keys_redis_key
python
def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank )
Return the Redis key for the SET of keys under a certain bank, given the bank name.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L281-L290
null
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), } def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) } def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank ) def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key ) def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value) def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks) def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
saltstack/salt
salt/cache/redis_cache.py
_build_bank_hier
python
def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True
Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L293-L310
null
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), } def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) } def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank ) def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key ) def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank ) def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value) def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks) def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
saltstack/salt
salt/cache/redis_cache.py
_get_banks_to_remove
python
def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove
A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L313-L330
null
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), } def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) } def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank ) def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key ) def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank ) def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value) def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks) def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
saltstack/salt
salt/cache/redis_cache.py
store
python
def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
Store the data in a Redis key.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L337-L357
[ "def _get_redis_server(opts=None):\n '''\n Return the Redis server instance.\n Caching the object instance.\n '''\n global REDIS_SERVER\n if REDIS_SERVER:\n return REDIS_SERVER\n if not opts:\n opts = _get_redis_cache_opts()\n\n if opts['cluster_mode']:\n REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'],\n skip_full_coverage_check=opts['skip_full_coverage_check'])\n else:\n REDIS_SERVER = redis.StrictRedis(opts['host'],\n opts['port'],\n unix_socket_path=opts['unix_socket_path'],\n db=opts['db'],\n password=opts['password'])\n return REDIS_SERVER\n", "def _get_key_redis_key(bank, key):\n '''\n Return the Redis key given the bank name and the key name.\n '''\n opts = _get_redis_keys_opts()\n return '{prefix}{separator}{bank}/{key}'.format(\n prefix=opts['key_prefix'],\n separator=opts['separator'],\n bank=bank,\n key=key\n )\n", "def _get_bank_keys_redis_key(bank):\n '''\n Return the Redis key for the SET of keys under a certain bank, given the bank name.\n '''\n opts = _get_redis_keys_opts()\n return '{prefix}{separator}{bank}'.format(\n prefix=opts['bank_keys_prefix'],\n separator=opts['separator'],\n bank=bank\n )\n", "def _build_bank_hier(bank, redis_pipe):\n '''\n Build the bank hierarchy from the root of the tree.\n If already exists, it won't rewrite.\n It's using the Redis pipeline,\n so there will be only one interaction with the remote server.\n '''\n bank_list = bank.split('/')\n parent_bank_path = bank_list[0]\n for bank_name in bank_list[1:]:\n prev_bank_redis_key = _get_bank_redis_key(parent_bank_path)\n redis_pipe.sadd(prev_bank_redis_key, bank_name)\n log.debug('Adding %s to %s', bank_name, prev_bank_redis_key)\n parent_bank_path = '{curr_path}/{bank_name}'.format(\n curr_path=parent_bank_path,\n bank_name=bank_name\n ) # this becomes the parent of the next\n return True\n" ]
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), } def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) } def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank ) def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key ) def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank ) def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value) def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks) def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
saltstack/salt
salt/cache/redis_cache.py
fetch
python
def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value)
Fetch data from the Redis cache.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L360-L376
[ "def _get_redis_server(opts=None):\n '''\n Return the Redis server instance.\n Caching the object instance.\n '''\n global REDIS_SERVER\n if REDIS_SERVER:\n return REDIS_SERVER\n if not opts:\n opts = _get_redis_cache_opts()\n\n if opts['cluster_mode']:\n REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'],\n skip_full_coverage_check=opts['skip_full_coverage_check'])\n else:\n REDIS_SERVER = redis.StrictRedis(opts['host'],\n opts['port'],\n unix_socket_path=opts['unix_socket_path'],\n db=opts['db'],\n password=opts['password'])\n return REDIS_SERVER\n", "def _get_key_redis_key(bank, key):\n '''\n Return the Redis key given the bank name and the key name.\n '''\n opts = _get_redis_keys_opts()\n return '{prefix}{separator}{bank}/{key}'.format(\n prefix=opts['key_prefix'],\n separator=opts['separator'],\n bank=bank,\n key=key\n )\n" ]
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), } def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) } def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank ) def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key ) def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank ) def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks) def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
saltstack/salt
salt/cache/redis_cache.py
flush
python
def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True
Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L379-L471
[ "def _get_redis_server(opts=None):\n '''\n Return the Redis server instance.\n Caching the object instance.\n '''\n global REDIS_SERVER\n if REDIS_SERVER:\n return REDIS_SERVER\n if not opts:\n opts = _get_redis_cache_opts()\n\n if opts['cluster_mode']:\n REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'],\n skip_full_coverage_check=opts['skip_full_coverage_check'])\n else:\n REDIS_SERVER = redis.StrictRedis(opts['host'],\n opts['port'],\n unix_socket_path=opts['unix_socket_path'],\n db=opts['db'],\n password=opts['password'])\n return REDIS_SERVER\n", "def _get_bank_redis_key(bank):\n '''\n Return the Redis key for the bank given the name.\n '''\n opts = _get_redis_keys_opts()\n return '{prefix}{separator}{bank}'.format(\n prefix=opts['bank_prefix'],\n separator=opts['separator'],\n bank=bank\n )\n", "def _get_key_redis_key(bank, key):\n '''\n Return the Redis key given the bank name and the key name.\n '''\n opts = _get_redis_keys_opts()\n return '{prefix}{separator}{bank}/{key}'.format(\n prefix=opts['key_prefix'],\n separator=opts['separator'],\n bank=bank,\n key=key\n )\n", "def _get_bank_keys_redis_key(bank):\n '''\n Return the Redis key for the SET of keys under a certain bank, given the bank name.\n '''\n opts = _get_redis_keys_opts()\n return '{prefix}{separator}{bank}'.format(\n prefix=opts['bank_keys_prefix'],\n separator=opts['separator'],\n bank=bank\n )\n", "def _get_banks_to_remove(redis_server, bank, path=''):\n '''\n A simple tree tarversal algorithm that builds the list of banks to remove,\n starting from an arbitrary node in the tree.\n '''\n current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank)\n bank_paths_to_remove = [current_path]\n # as you got here, you'll be removed\n\n bank_key = _get_bank_redis_key(current_path)\n child_banks = redis_server.smembers(bank_key)\n if not child_banks:\n return bank_paths_to_remove # this bank does not have any child banks so we stop here\n for child_bank in child_banks:\n bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path))\n # go one more level deeper\n # and also remove the children of this child bank (if any)\n return bank_paths_to_remove\n" ]
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), } def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) } def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank ) def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key ) def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank ) def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value) def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks) def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
saltstack/salt
salt/cache/redis_cache.py
list_
python
def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks)
Lists entries stored in the specified bank.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L474-L489
[ "def _get_redis_server(opts=None):\n '''\n Return the Redis server instance.\n Caching the object instance.\n '''\n global REDIS_SERVER\n if REDIS_SERVER:\n return REDIS_SERVER\n if not opts:\n opts = _get_redis_cache_opts()\n\n if opts['cluster_mode']:\n REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'],\n skip_full_coverage_check=opts['skip_full_coverage_check'])\n else:\n REDIS_SERVER = redis.StrictRedis(opts['host'],\n opts['port'],\n unix_socket_path=opts['unix_socket_path'],\n db=opts['db'],\n password=opts['password'])\n return REDIS_SERVER\n", "def _get_bank_redis_key(bank):\n '''\n Return the Redis key for the bank given the name.\n '''\n opts = _get_redis_keys_opts()\n return '{prefix}{separator}{bank}'.format(\n prefix=opts['bank_prefix'],\n separator=opts['separator'],\n bank=bank\n )\n" ]
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), } def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) } def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank ) def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key ) def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank ) def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value) def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
saltstack/salt
salt/cache/redis_cache.py
contains
python
def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
Checks if the specified bank contains the specified key.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L492-L504
[ "def _get_redis_server(opts=None):\n '''\n Return the Redis server instance.\n Caching the object instance.\n '''\n global REDIS_SERVER\n if REDIS_SERVER:\n return REDIS_SERVER\n if not opts:\n opts = _get_redis_cache_opts()\n\n if opts['cluster_mode']:\n REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'],\n skip_full_coverage_check=opts['skip_full_coverage_check'])\n else:\n REDIS_SERVER = redis.StrictRedis(opts['host'],\n opts['port'],\n unix_socket_path=opts['unix_socket_path'],\n db=opts['db'],\n password=opts['password'])\n return REDIS_SERVER\n", "def _get_bank_redis_key(bank):\n '''\n Return the Redis key for the bank given the name.\n '''\n opts = _get_redis_keys_opts()\n return '{prefix}{separator}{bank}'.format(\n prefix=opts['bank_prefix'],\n separator=opts['separator'],\n bank=bank\n )\n" ]
# -*- coding: utf-8 -*- ''' Redis ===== Redis plugin for the Salt caching subsystem. .. versionadded:: 2017.7.0 As Redis provides a simple mechanism for very fast key-value store, in order to privde the necessary features for the Salt caching subsystem, the following conventions are used: - A Redis key consists of the bank name and the cache key separated by ``/``, e.g.: ``$KEY_minions/alpha/stuff`` where ``minions/alpha`` is the bank name and ``stuff`` is the key name. - As the caching subsystem is organised as a tree, we need to store the caching path and identify the bank and its offspring. At the same time, Redis is linear and we need to avoid doing ``keys <pattern>`` which is very inefficient as it goes through all the keys on the remote Redis server. Instead, each bank hierarchy has a Redis SET associated which stores the list of sub-banks. By default, these keys begin with ``$BANK_``. - In addition, each key name is stored in a separate SET of all the keys within a bank. By default, these SETs begin with ``$BANKEYS_``. For example, to store the key ``my-key`` under the bank ``root-bank/sub-bank/leaf-bank``, the following hierarchy will be built: .. code-block:: text 127.0.0.1:6379> SMEMBERS $BANK_root-bank 1) "sub-bank" 127.0.0.1:6379> SMEMBERS $BANK_root-bank/sub-bank 1) "leaf-bank" 127.0.0.1:6379> SMEMBERS $BANKEYS_root-bank/sub-bank/leaf-bank 1) "my-key" 127.0.0.1:6379> GET $KEY_root-bank/sub-bank/leaf-bank/my-key "my-value" There are three types of keys stored: - ``$BANK_*`` is a Redis SET containing the list of banks under the current bank - ``$BANKEYS_*`` is a Redis SET containing the list of keys under the current bank - ``$KEY_*`` keeps the value of the key These prefixes and the separator can be adjusted using the configuration options: bank_prefix: ``$BANK`` The prefix used for the name of the Redis key storing the list of sub-banks. bank_keys_prefix: ``$BANKEYS`` The prefix used for the name of the Redis keyt storing the list of keys under a certain bank. key_prefix: ``$KEY`` The prefix of the Redis keys having the value of the keys to be cached under a certain bank. separator: ``_`` The separator between the prefix and the key body. The connection details can be specified using: host: ``localhost`` The hostname of the Redis server. port: ``6379`` The Redis server port. cluster_mode: ``False`` Whether cluster_mode is enabled or not cluster.startup_nodes: A list of host, port dictionaries pointing to cluster members. At least one is required but multiple nodes are better .. code-block:: yaml cache.redis.cluster.startup_nodes - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cluster.skip_full_coverage_check: ``False`` Some cluster providers restrict certain redis commands such as CONFIG for enhanced security. Set this option to true to skip checks that required advanced privileges. .. note:: Most cloud hosted redis clusters will require this to be set to ``True`` db: ``'0'`` The database index. .. note:: The database index must be specified as string not as integer value! password: Redis connection password. unix_socket_path: .. versionadded:: 2018.3.1 Path to a UNIX socket for access. Overrides `host` / `port`. Configuration Example: .. code-block:: yaml cache.redis.host: localhost cache.redis.port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' Cluster Configuration Example: .. code-block:: yaml cache.redis.cluster_mode: true cache.redis.cluster.skip_full_coverage_check: true cache.redis.cluster.startup_nodes: - host: redis-member-1 port: 6379 - host: redis-member-2 port: 6379 cache.redis.db: '0' cache.redis.password: my pass cache.redis.bank_prefix: #BANK cache.redis.bank_keys_prefix: #BANKEYS cache.redis.key_prefix: #KEY cache.redis.separator: '@' ''' from __future__ import absolute_import, print_function, unicode_literals # Import stdlib import logging # Import third party libs try: import redis from redis.exceptions import ConnectionError as RedisConnectionError from redis.exceptions import ResponseError as RedisResponseError HAS_REDIS = True except ImportError: HAS_REDIS = False try: from rediscluster import StrictRedisCluster HAS_REDIS_CLUSTER = True except ImportError: HAS_REDIS_CLUSTER = False # Import salt from salt.ext.six.moves import range from salt.exceptions import SaltCacheError # ----------------------------------------------------------------------------- # module properties # ----------------------------------------------------------------------------- __virtualname__ = 'redis' __func_alias__ = {'list_': 'list'} log = logging.getLogger(__file__) _BANK_PREFIX = '$BANK' _KEY_PREFIX = '$KEY' _BANK_KEYS_PREFIX = '$BANKEYS' _SEPARATOR = '_' REDIS_SERVER = None # ----------------------------------------------------------------------------- # property functions # ----------------------------------------------------------------------------- def __virtual__(): ''' The redis library must be installed for this module to work. The redis redis cluster library must be installed if cluster_mode is True ''' if not HAS_REDIS: return (False, "Please install the python-redis package.") if not HAS_REDIS_CLUSTER and _get_redis_cache_opts()['cluster_mode']: return (False, "Please install the redis-py-cluster package.") return __virtualname__ # ----------------------------------------------------------------------------- # helper functions -- will not be exported # ----------------------------------------------------------------------------- def init_kwargs(kwargs): return {} def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), } def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) } def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank ) def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key ) def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank ) def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove # ----------------------------------------------------------------------------- # cache subsystem functions # ----------------------------------------------------------------------------- def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value) def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks)
saltstack/salt
salt/modules/boto_vpc.py
check_vpc
python
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L201-L228
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 _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 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_resource
python
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)}
Create a VPC resource. Returns the resource id if created, or False if not created.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L231-L278
[ "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", "def _maybe_set_name_tag(name, obj):\n if name:\n obj.add_tag(\"Name\", name)\n log.debug('%s is now named as %s', obj, name)\n", "def _maybe_set_tags(tags, obj):\n if tags:\n # Not all objects in Boto have an 'add_tags()' method.\n try:\n obj.add_tags(tags)\n\n except AttributeError:\n for tag, value in tags.items():\n obj.add_tag(tag, value)\n log.debug('The following tags: %s were added to %s', ', '.join(tags), obj)\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 _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 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_resource
python
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)}
Delete a VPC resource. Returns True if successful, otherwise False.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L281-L322
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 _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 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_resource
python
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
Get a VPC resource based on resource type and name or id. Cache the id if name was provided.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L325-L370
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 _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 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
_find_resources
python
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
Get VPC resources based on resource type and name, id, or tags.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L373-L409
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 _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 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_resource_id
python
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
Get an AWS id for a VPC resource by type and name.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L412-L428
[ "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=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 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_resource_id
python
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)}
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L431-L450
[ "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 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 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
resource_exists
python
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)}
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L453-L477
[ "def _find_resources(resource, name=None, resource_id=None, tags=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n Get VPC resources based on resource type and name, id, or tags.\n '''\n\n if all((resource_id, name)):\n raise SaltInvocationError('Only one of name or id may be '\n 'provided.')\n\n if not any((resource_id, name, tags)):\n raise SaltInvocationError('At least one of the following must be '\n 'provided: id, name, or tags.')\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\n filter_parameters = {}\n if name:\n filter_parameters['filters'] = {'tag:Name': name}\n if resource_id:\n filter_parameters['{0}_ids'.format(resource)] = resource_id\n if tags:\n for tag_name, tag_value in six.iteritems(tags):\n filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value\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 return r\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 _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 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_id
python
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
Given VPC properties, return the VPC id if a match is found.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L521-L549
[ "def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,\n region=None, key=None, keyid=None, profile=None):\n\n '''\n Given VPC properties, find and return matching VPC ids.\n '''\n\n if all((vpc_id, vpc_name)):\n raise SaltInvocationError('Only one of vpc_name or vpc_id may be '\n 'provided.')\n\n if not any((vpc_id, vpc_name, tags, cidr)):\n raise SaltInvocationError('At least one of the following must be '\n 'provided: vpc_id, vpc_name, cidr or tags.')\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n filter_parameters = {'filters': {}}\n\n if vpc_id:\n filter_parameters['vpc_ids'] = [vpc_id]\n\n if cidr:\n filter_parameters['filters']['cidr'] = cidr\n\n if vpc_name:\n filter_parameters['filters']['tag:Name'] = vpc_name\n\n if tags:\n for tag_name, tag_value in six.iteritems(tags):\n filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value\n\n vpcs = conn.get_all_vpcs(**filter_parameters)\n log.debug('The filters criteria %s matched the following VPCs:%s',\n filter_parameters, vpcs)\n\n if vpcs:\n return [vpc.id for vpc in vpcs]\n else:\n return []\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(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 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_id
python
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)}
Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L552-L569
[ "def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None,\n keyid=None, profile=None):\n '''\n Given VPC properties, return the VPC id if a match is found.\n '''\n\n if vpc_name and not any((cidr, tags)):\n vpc_id = _cache_id(vpc_name, region=region,\n key=key, keyid=keyid,\n profile=profile)\n if vpc_id:\n return vpc_id\n\n vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region,\n key=key, keyid=keyid, profile=profile)\n if vpc_ids:\n log.debug(\"Matching VPC: %s\", \" \".join(vpc_ids))\n if len(vpc_ids) == 1:\n vpc_id = vpc_ids[0]\n if vpc_name:\n _cache_id(vpc_name, vpc_id,\n region=region, key=key,\n keyid=keyid, profile=profile)\n return vpc_id\n else:\n raise CommandExecutionError('Found more than one VPC matching the criteria.')\n else:\n log.info('No VPC found.')\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 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 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
exists
python
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)}
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L572-L598
[ "def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,\n region=None, key=None, keyid=None, profile=None):\n\n '''\n Given VPC properties, find and return matching VPC ids.\n '''\n\n if all((vpc_id, vpc_name)):\n raise SaltInvocationError('Only one of vpc_name or vpc_id may be '\n 'provided.')\n\n if not any((vpc_id, vpc_name, tags, cidr)):\n raise SaltInvocationError('At least one of the following must be '\n 'provided: vpc_id, vpc_name, cidr or tags.')\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n filter_parameters = {'filters': {}}\n\n if vpc_id:\n filter_parameters['vpc_ids'] = [vpc_id]\n\n if cidr:\n filter_parameters['filters']['cidr'] = cidr\n\n if vpc_name:\n filter_parameters['filters']['tag:Name'] = vpc_name\n\n if tags:\n for tag_name, tag_value in six.iteritems(tags):\n filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value\n\n vpcs = conn.get_all_vpcs(**filter_parameters)\n log.debug('The filters criteria %s matched the following VPCs:%s',\n filter_parameters, vpcs)\n\n if vpcs:\n return [vpc.id for vpc in vpcs]\n else:\n return []\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 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 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
python
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)}
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'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L601-L642
[ "def _maybe_set_name_tag(name, obj):\n if name:\n obj.add_tag(\"Name\", name)\n log.debug('%s is now named as %s', obj, name)\n", "def _maybe_set_tags(tags, obj):\n if tags:\n # Not all objects in Boto have an 'add_tags()' method.\n try:\n obj.add_tags(tags)\n\n except AttributeError:\n for tag, value in tags.items():\n obj.add_tag(tag, value)\n log.debug('The following tags: %s were added to %s', ', '.join(tags), obj)\n", "def _maybe_set_dns(conn, vpcid, dns_support, dns_hostnames):\n if dns_support:\n conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_support=dns_support)\n log.debug('DNS support was set to: %s on vpc %s', dns_support, vpcid)\n if dns_hostnames:\n conn.modify_vpc_attribute(vpc_id=vpcid, enable_dns_hostnames=dns_hostnames)\n log.debug('DNS hostnames was set to: %s on vpc %s', dns_hostnames, vpcid)\n", "def _maybe_name_route_table(conn, vpcid, vpc_name):\n route_tables = conn.get_all_route_tables(filters={'vpc_id': vpcid})\n if not route_tables:\n log.warning('no default route table found')\n return\n default_table = None\n for table in route_tables:\n for association in getattr(table, 'associations', {}):\n if getattr(association, 'main', False):\n default_table = table\n break\n if not default_table:\n log.warning('no default route table found')\n return\n\n name = '{0}-default-table'.format(vpc_name)\n _maybe_set_name_tag(name, default_table)\n log.debug('Default route table name was set to: %s on vpc %s', name, vpcid)\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 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 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
python
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)}
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'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L645-L692
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 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 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
python
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}
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L695-L747
[ "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_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 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_vpcs
python
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)}
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L750-L805
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\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 _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 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
_find_subnets
python
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
Given subnet properties, find and return matching subnet ids
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L808-L839
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 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 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_subnet
python
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
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'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L842-L880
[ "def _create_resource(resource, name=None, tags=None, region=None, key=None,\n keyid=None, profile=None, **kwargs):\n '''\n Create a VPC resource. Returns the resource id if created, or False\n if not created.\n '''\n\n try:\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n create_resource = getattr(conn, 'create_' + resource)\n except AttributeError:\n raise AttributeError('{0} function does not exist for boto VPC '\n 'connection.'.format('create_' + resource))\n\n if name and _get_resource_id(resource, name, region=region, key=key,\n keyid=keyid, profile=profile):\n return {'created': False, 'error': {'message':\n 'A {0} named {1} already exists.'.format(\n resource, name)}}\n\n r = create_resource(**kwargs)\n\n if r:\n if isinstance(r, bool):\n return {'created': True}\n else:\n log.info('A %s with id %s was created', resource, r.id)\n _maybe_set_name_tag(name, r)\n _maybe_set_tags(tags, r)\n\n if name:\n _cache_id(name,\n sub_resource=resource,\n resource_id=r.id,\n region=region,\n key=key, keyid=keyid,\n profile=profile)\n return {'created': True, 'id': r.id}\n else:\n if name:\n e = '{0} {1} was not created.'.format(resource, name)\n else:\n e = '{0} was not created.'.format(resource)\n log.warning(e)\n return {'created': False, 'error': {'message': e}}\n except BotoServerError as e:\n return {'created': False, 'error': __utils__['boto.get_error'](e)}\n", "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 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 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_subnet
python
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)
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'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L883-L903
[ "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 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 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
subnet_exists
python
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}
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'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L906-L969
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 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 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_association
python
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)}
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']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L972-L1015
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 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 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_subnet
python
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1018-L1053
[ "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", "def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None):\n '''\n helper function to find subnet explicit route table associations\n\n .. versionadded:: 2016.11.0\n '''\n if not conn:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if conn:\n vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id})\n for vpc_route_table in vpc_route_tables:\n for rt_association in vpc_route_table.associations:\n if rt_association.subnet_id == subnet_id and not rt_association.main:\n return rt_association.id\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_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 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_subnets
python
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)}
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1056-L1120
[ "def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None):\n '''\n helper function to find subnet explicit route table associations\n\n .. versionadded:: 2016.11.0\n '''\n if not conn:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if conn:\n vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id})\n for vpc_route_table in vpc_route_tables:\n for rt_association in vpc_route_table.associations:\n if rt_association.subnet_id == subnet_id and not rt_association.main:\n return rt_association.id\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 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 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_internet_gateway
python
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)}
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1123-L1162
[ "def _create_resource(resource, name=None, tags=None, region=None, key=None,\n keyid=None, profile=None, **kwargs):\n '''\n Create a VPC resource. Returns the resource id if created, or False\n if not created.\n '''\n\n try:\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n create_resource = getattr(conn, 'create_' + resource)\n except AttributeError:\n raise AttributeError('{0} function does not exist for boto VPC '\n 'connection.'.format('create_' + resource))\n\n if name and _get_resource_id(resource, name, region=region, key=key,\n keyid=keyid, profile=profile):\n return {'created': False, 'error': {'message':\n 'A {0} named {1} already exists.'.format(\n resource, name)}}\n\n r = create_resource(**kwargs)\n\n if r:\n if isinstance(r, bool):\n return {'created': True}\n else:\n log.info('A %s with id %s was created', resource, r.id)\n _maybe_set_name_tag(name, r)\n _maybe_set_tags(tags, r)\n\n if name:\n _cache_id(name,\n sub_resource=resource,\n resource_id=r.id,\n region=region,\n key=key, keyid=keyid,\n profile=profile)\n return {'created': True, 'id': r.id}\n else:\n if name:\n e = '{0} {1} was not created.'.format(resource, name)\n else:\n e = '{0} was not created.'.format(resource)\n log.warning(e)\n return {'created': False, 'error': {'message': e}}\n except BotoServerError as e:\n return {'created': False, 'error': __utils__['boto.get_error'](e)}\n", "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 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 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_internet_gateway
python
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)}
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1165-L1216
[ "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_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", "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 _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 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
_find_nat_gateways
python
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
Given gateway properties, find and return matching nat gateways
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1219-L1269
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 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 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
nat_gateway_exists
python
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))
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'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1272-L1299
[ "def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None,\n states=('pending', 'available'),\n region=None, key=None, keyid=None, profile=None):\n '''\n Given gateway properties, find and return matching nat gateways\n '''\n\n if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)):\n raise SaltInvocationError('At least one of the following must be '\n 'provided: nat_gateway_id, subnet_id, '\n 'subnet_name, vpc_id, or vpc_name.')\n filter_parameters = {'Filter': []}\n\n if nat_gateway_id:\n filter_parameters['NatGatewayIds'] = [nat_gateway_id]\n\n if subnet_name:\n subnet_id = _get_resource_id('subnet', subnet_name,\n region=region, key=key,\n keyid=keyid, profile=profile)\n if not subnet_id:\n return False\n\n if subnet_id:\n filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]})\n\n if vpc_name:\n vpc_id = _get_resource_id('vpc', vpc_name,\n region=region, key=key,\n keyid=keyid, profile=profile)\n if not vpc_id:\n return False\n\n if vpc_id:\n filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]})\n\n conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n nat_gateways = []\n for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways,\n marker_flag='NextToken', marker_arg='NextToken',\n **filter_parameters):\n for gw in ret.get('NatGateways', []):\n if gw.get('State') in states:\n nat_gateways.append(gw)\n log.debug('The filters criteria %s matched the following nat gateways: %s',\n filter_parameters, nat_gateways)\n\n if nat_gateways:\n return nat_gateways\n else:\n return False\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 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 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_nat_gateways
python
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)
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'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1302-L1327
[ "def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None,\n states=('pending', 'available'),\n region=None, key=None, keyid=None, profile=None):\n '''\n Given gateway properties, find and return matching nat gateways\n '''\n\n if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)):\n raise SaltInvocationError('At least one of the following must be '\n 'provided: nat_gateway_id, subnet_id, '\n 'subnet_name, vpc_id, or vpc_name.')\n filter_parameters = {'Filter': []}\n\n if nat_gateway_id:\n filter_parameters['NatGatewayIds'] = [nat_gateway_id]\n\n if subnet_name:\n subnet_id = _get_resource_id('subnet', subnet_name,\n region=region, key=key,\n keyid=keyid, profile=profile)\n if not subnet_id:\n return False\n\n if subnet_id:\n filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]})\n\n if vpc_name:\n vpc_id = _get_resource_id('vpc', vpc_name,\n region=region, key=key,\n keyid=keyid, profile=profile)\n if not vpc_id:\n return False\n\n if vpc_id:\n filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]})\n\n conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n nat_gateways = []\n for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways,\n marker_flag='NextToken', marker_arg='NextToken',\n **filter_parameters):\n for gw in ret.get('NatGateways', []):\n if gw.get('State') in states:\n nat_gateways.append(gw)\n log.debug('The filters criteria %s matched the following nat gateways: %s',\n filter_parameters, nat_gateways)\n\n if nat_gateways:\n return nat_gateways\n else:\n return False\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 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 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_nat_gateway
python
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)}
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1330-L1380
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 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 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_nat_gateway
python
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)}
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1383-L1456
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 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 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_customer_gateway
python
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)
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1459-L1482
[ "def _create_resource(resource, name=None, tags=None, region=None, key=None,\n keyid=None, profile=None, **kwargs):\n '''\n Create a VPC resource. Returns the resource id if created, or False\n if not created.\n '''\n\n try:\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n create_resource = getattr(conn, 'create_' + resource)\n except AttributeError:\n raise AttributeError('{0} function does not exist for boto VPC '\n 'connection.'.format('create_' + resource))\n\n if name and _get_resource_id(resource, name, region=region, key=key,\n keyid=keyid, profile=profile):\n return {'created': False, 'error': {'message':\n 'A {0} named {1} already exists.'.format(\n resource, name)}}\n\n r = create_resource(**kwargs)\n\n if r:\n if isinstance(r, bool):\n return {'created': True}\n else:\n log.info('A %s with id %s was created', resource, r.id)\n _maybe_set_name_tag(name, r)\n _maybe_set_tags(tags, r)\n\n if name:\n _cache_id(name,\n sub_resource=resource,\n resource_id=r.id,\n region=region,\n key=key, keyid=keyid,\n profile=profile)\n return {'created': True, 'id': r.id}\n else:\n if name:\n e = '{0} {1} was not created.'.format(resource, name)\n else:\n e = '{0} was not created.'.format(resource)\n log.warning(e)\n return {'created': False, 'error': {'message': e}}\n except BotoServerError as e:\n return {'created': 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 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 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_customer_gateway
python
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)
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'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1485-L1507
[ "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 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 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
customer_gateway_exists
python
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)
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1510-L1528
[ "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 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 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_dhcp_options
python
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)}
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'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1531-L1577
[ "def _create_resource(resource, name=None, tags=None, region=None, key=None,\n keyid=None, profile=None, **kwargs):\n '''\n Create a VPC resource. Returns the resource id if created, or False\n if not created.\n '''\n\n try:\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n create_resource = getattr(conn, 'create_' + resource)\n except AttributeError:\n raise AttributeError('{0} function does not exist for boto VPC '\n 'connection.'.format('create_' + resource))\n\n if name and _get_resource_id(resource, name, region=region, key=key,\n keyid=keyid, profile=profile):\n return {'created': False, 'error': {'message':\n 'A {0} named {1} already exists.'.format(\n resource, name)}}\n\n r = create_resource(**kwargs)\n\n if r:\n if isinstance(r, bool):\n return {'created': True}\n else:\n log.info('A %s with id %s was created', resource, r.id)\n _maybe_set_name_tag(name, r)\n _maybe_set_tags(tags, r)\n\n if name:\n _cache_id(name,\n sub_resource=resource,\n resource_id=r.id,\n region=region,\n key=key, keyid=keyid,\n profile=profile)\n return {'created': True, 'id': r.id}\n else:\n if name:\n e = '{0} {1} was not created.'.format(resource, name)\n else:\n e = '{0} was not created.'.format(resource)\n log.warning(e)\n return {'created': False, 'error': {'message': e}}\n except BotoServerError as e:\n return {'created': False, 'error': __utils__['boto.get_error'](e)}\n", "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 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 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_dhcp_options
python
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)}
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1580-L1616
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 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 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_dhcp_options
python
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)
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'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1619-L1638
[ "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 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 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)