Skip to content

Instantly share code, notes, and snippets.

@sergray
Last active August 29, 2015 14:00
Show Gist options
  • Save sergray/11393725 to your computer and use it in GitHub Desktop.
Save sergray/11393725 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""Describe EC2 instances bound to DNS name. Lookup CNAME of DNS,
which can point to ELB or EC2 instance. Get info from AWS API.
DNS names should be passed as arguments to the script.
Valid AWS API credentials must be configured, see
http://docs.pythonboto.org/en/latest/getting_started.html#configuring-boto-credentials
"""
from __future__ import print_function
from subprocess import check_output
import boto.ec2
import boto.ec2.elb
import sys
import operator
ELB_DNS_SUFFIX = 'elb.amazonaws.com.'
EC2_DNS_SUFFIX = 'compute.amazonaws.com.'
def discover_elb(cname, region_name):
elb_svc = boto.ec2.elb.connect_to_region(region_name)
load_balancers = [elb for elb in elb_svc.get_all_load_balancers() if cname.startswith(elb.dns_name)]
if not load_balancers:
print("Did not find load balancer by CNAME", cname)
sys.exit(1)
elb = load_balancers[0]
ec2_svc = boto.ec2.connect_to_region(elb.connection.region.name)
reservations = ec2_svc.get_all_instances(instance_ids=[inst.id for inst in elb.instances])
print("ELB", elb.dns_name, "instances:")
report_instances(reservations)
def discover_ec2(cname, region_name):
if region_name == 'compute-1':
region_name = 'us-east-1'
ec2_svc = boto.ec2.connect_to_region(region_name)
reservations = ec2_svc.get_all_instances()
print("CNAME", cname, "instance:")
report_instances(reservations,
instance_filter=lambda inst: \
inst.state == 'running' and cname.startswith(inst.dns_name))
CNAME_HANDLERS = {
ELB_DNS_SUFFIX: discover_elb,
EC2_DNS_SUFFIX: discover_ec2,
'amazonaws.com.': discover_ec2,
}
def discover(dns_name):
cname = check_output(['dig', '+short', dns_name, 'CNAME']).rstrip()
if not cname:
print("Did not find CNAME for", dns_name)
sys.exit(1)
try:
aws_id, region_name, aws_suffix = cname.split('.', 2)
cname_handler = CNAME_HANDLERS[aws_suffix]
except (ValueError, KeyError):
print("Do not know how to handle", cname)
sys.exit(1)
else:
cname_handler(cname, region_name)
def report_instances(reservations, instance_filter=None):
instances = reduce(operator.add, (r.instances for r in reservations))
if callable(instance_filter):
instances = [inst for inst in instances if instance_filter(inst)]
for o in instances:
print(
o.state, o.instance_type,
o.dns_name if hasattr(o, 'dns_name') else '',
'in', o.placement)
if __name__ == '__main__':
for dns_name in sys.argv[1:]:
print("DNS", dns_name)
discover(dns_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment