Skip to content

Instantly share code, notes, and snippets.

@wica128
Created January 15, 2018 12:04
Show Gist options
  • Save wica128/71e8b1e89716c01edcc1d70d93d3ca26 to your computer and use it in GitHub Desktop.
Save wica128/71e8b1e89716c01edcc1d70d93d3ca26 to your computer and use it in GitHub Desktop.
Ansible, get VPC ID by name
./lookup_plugins/ec2_vpc_find_id.py
#
# Lookup VPC ID by name
#
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables, **kwargs):
vpcs = variables.get('vpc_facts')
for vpc in vpcs['vpcs']:
if terms[0] == vpc['tags']['Name']:
return [ vpc['id'] ]
return []
In a role:
- ec2_vpc_net_facts:
region: "{{ region }}"
register: vpc_facts
- name: show templating results
debug:
msg: "{{ lookup('custom', 'test-vpc') }}"
# Find VPC if we a VPC and what it's ID is.
- name: Setting up a subnet
ec2_vpc_subnet:
vpc_id: "{{ lookup('ec2_vpc_find_id', item.vpc_name) }}"
cidr: "{{ item.cidr }}"
region: "{{ item.region | default(region)}}"
state: "{{ item.state | default('present')}}"
az: "{{ region }}{{ item.az }}"
map_public: "{{ item.map_public | default('no') }}"
tags:
name: "{{ item.name }}"
customer: "{{ customer }}"
group: "{{ group }}"
environment: "{{ env }}"
with_items: "{{ subnets }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment