Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Discover ec2 instances by tag and tag value
from boto import ec2
class Resource(object):
"""
Represents a single resource returned from the Discovery class's
get_resources method.
"""
def __init__(self, host_name, private_host_name, ip, private_ip, tags):
self.__host_name = host_name
self.__private_host_name = private_host_name
self.__ip = ip
self.__private_ip = private_ip
self.__tags = tags
@property
def host_name(self):
return self.__host_name
@property
def private_host_name(self):
return self.__private_host_name
@property
def ip(self):
return self.__ip
@property
def private_ip(self):
return self.__private_ip
@property
def tags(self):
return self.__tags
class Discovery(object):
def __init__(self, region):
self.__ec2conn = None
self.__ec2conn = ec2.connect_to_region(region,
aws_access_key_id="<An AWS access key>",
aws_secret_access_key="<An AWS secret key>")
if self.__ec2conn is None:
raise Exception("ec2 discovery: connection to region {} failed.".format(region))
def get_resources(self, tag=None, tag_value=None):
"""
Returns the list of all running resources tagged with the named tag
having the passed value. If the value is None all running resources having
the tag are returned. If tag is None all running resources are returned.
"""
result = []
reservations = self.__ec2conn.get_all_instances()
for res in reservations:
for inst in res.instances:
if inst.state != 'running':
continue
if tag is None:
result.append(inst)
continue
if tag not in inst.tags:
continue
if tag_value is None:
result.append(inst)
continue
if inst.tags[tag].lower() == tag_value.lower():
result.append(inst)
for i in range(0, len(result)):
inst = result[i]
tags = dict()
for tag in inst.tags:
tags[tag] = inst.tags[tag]
resource = Resource(inst.dns_name, inst.private_dns_name,
inst.ip_address, inst.private_ip_address, tags)
result[i] = resource
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.