Skip to content

Instantly share code, notes, and snippets.

@andrewwatts
Created December 21, 2010 06:46
Show Gist options
  • Save andrewwatts/749591 to your computer and use it in GitHub Desktop.
Save andrewwatts/749591 to your computer and use it in GitHub Desktop.
print an /etc/hosts file to stdout with ec2 instances
#! /usr/bin/env python
# ##########
#
# Usage:
# ec2_hosts.py
#
# Then copy results to /etc/hosts
#
# ##########
import re
import shutil
import subprocess
process = subprocess.Popen('ec2-describe-instances | grep ^INSTANCE | grep running | cut -f 2,4,5,17,18', shell=True, stdout=subprocess.PIPE)
stdout_value = process.communicate()[0]
host_lines = []
for line in stdout_value.split('\n'):
try:
(instance, external_dns, internal_dns, external_ip, internal_ip) = line.split();
external_name,internal_name = external_ip,internal_ip
external_name = 'ec2-' + external_name.replace('.', '-')
internal_name = 'ip-' + internal_name.replace('.', '-')
host_line = '%s\t%s %s %s %s %s' % (external_ip, instance, internal_name, external_name, internal_dns, external_dns)
host_lines.append(host_line)
except:
pass
new_ec2_part = '# EC2_HOSTS\n%s\n# END_EC2_HOSTS\n' % ('\n'.join(host_lines))
ec2_re = re.compile('^# EC2_HOSTS$.*# END_EC2_HOSTS', re.DOTALL|re.MULTILINE)
hosts_file = open('/etc/hosts').read()
new_hosts_file = ec2_re.sub(new_ec2_part, hosts_file)
shutil.copyfile('/etc/hosts', '/tmp/hosts')
print new_hosts_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment