Skip to content

Instantly share code, notes, and snippets.

@rohitkothari
Created April 24, 2016 03:56
Show Gist options
  • Save rohitkothari/4f9423bc44b3eec54bf3334444edf119 to your computer and use it in GitHub Desktop.
Save rohitkothari/4f9423bc44b3eec54bf3334444edf119 to your computer and use it in GitHub Desktop.
Ansible Lookup plugin (v1.x) to get list of AWS EC2 Instance IDs given the value of Name tag
# A Lookup plugin to lookup EC2 instance IDs with given Name tag
# The plugin accepts instance name, i.e. the value for Name tag
# and returns a list of Instance IDs with that Name tag
# USAGE:
# - debug: msg="{{ lookup('lookup_ec2', instance_name) }}"
# OR
# with_lookup_ec2: "{{ instance_name }}"
from ansible.errors import *
from ansible import utils, errors
try:
import boto.ec2
except ImportError:
raise AnsibleError("Failed to load boto.ec2 while running lookup_ec2")
class LookupModule(object):
def __init__(self, basedir=None, **kwargs):
self.basedir = basedir
def run(self, terms, inject=None, **kwargs):
instance_name = terms
region = 'us-west-2'
try:
list_instances = describe_instances(instance_name,region)
except:
raise AnsibleError("Ansible error during lookup of instance: %s" % instance_name)
return list_instances
def describe_instances(instance_name,region):
list_instances = []
con = boto.ec2.connect_to_region(region)
reservations = con.get_all_instances(filters={"tag:Name" : instance_name})
for r in reservations:
for instances in r.instances:
list_instances.append(instances.id)
if len(list_instances) > 0:
return list_instances
else:
print("Lookup result: No instance found")
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment