Skip to content

Instantly share code, notes, and snippets.

@hamsolodev
Last active December 20, 2015 19:18
Show Gist options
  • Save hamsolodev/6181881 to your computer and use it in GitHub Desktop.
Save hamsolodev/6181881 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
#
# Retrieve a list of hosts from EC2, with Name metadata tags matching
# the supplied regex.
#
# e.g. in your fabfile
#
# env.roledefs = {
# 'somesite': lambda: matching_names(r'somesite-web-\d+'),
# }
#
import re
import boto.ec2
def matching_names(name_regex, region='ap-southeast-2',
public_dns_names=False):
"""Queries AWS EC2 for instances whose 'name' metadata matches
the supplied regex.
Note this depends on boto being able to authenticate with
AWS. This is achieved by setting two environment variables:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
TODO: maybe more intelligently return hosts based on their
“accessibility” status.
"""
conn = boto.ec2.connect_to_region(region)
# fetch instance ids whose 'name' tag matches the supplied regex
instances = {}
for tag in conn.get_all_tags():
if tag.name == 'Name' and re.match(name_regex, tag.value):
# store the 'name' tag's full value
instances.update({tag.res_id: tag.value})
if not instances:
# no running instances 'name' tag matched the supplied regex,
# so return an empty list
return []
else:
# fetch addresses for the instances fetched earlier
hostlist = []
for ec2_i in conn.get_all_instances():
if ec2_i.instances[0].id in instances.keys():
hostlist.append(
public_dns_names and ec2_i.instances[0].public_dns_name \
or ec2_i.instances[0].private_dns_name)
return hostlist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment