Created
June 7, 2012 14:44
-
-
Save apg/2889184 to your computer and use it in GitHub Desktop.
Write a hosts file based on all the current instances in 'running' state on EC2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import os | |
import boto | |
from optparse import OptionParser | |
from contextlib import closing | |
parser = OptionParser() | |
parser.add_option('-a', '--access-key', default=None, dest='access_key', | |
help="AWS access key (required)") | |
parser.add_option('-d', '--domain', default=None, dest='domain', | |
help="Top-level domain") | |
parser.add_option('-s', '--secret-key', default=None, dest='secret_key', | |
help="AWS secret key (required)") | |
parser.add_option('-o', '--output', default=None, dest='output', | |
help="Output file (defaults to stdout)") | |
def open_output(f): | |
if f == None or f == '-': | |
fd = sys.stdout.fileno() | |
return os.fdopen(fd, 'w') | |
else: | |
return open(f, 'w') | |
def write_hosts(access, secret, domain, output): | |
conn = boto.connect_ec2(access, secret) | |
instances = conn.get_all_instances() | |
fmt = '' | |
if domain: | |
fmt = '%(ip)s %(name)s.int %(name)s.int.%(domain)s' | |
else: | |
fmt = '%(ip)s %(name)s.int' | |
lines = ['127.0.0.1 localhost localhost.localdomain'] | |
for ins in instances: | |
for i in ins.instances: | |
if i.state == 'running' and 'Name' in i.tags: | |
if len(i.tags['Name']) == 0: | |
continue | |
lines.append(fmt % {'ip': i.private_ip_address, | |
'name': i.tags['Name'], | |
'domain': domain}) | |
if len(lines) > 1: | |
with closing(open_output(output)) as out: | |
out.write('\n'.join(lines)) | |
out.write('\n') | |
return True | |
return False | |
if __name__ == '__main__': | |
(options, args) = parser.parse_args() | |
output = None | |
if len(args) > 0: | |
sys.stderr.write("ERROR: no extra args needed!\n") | |
parser.print_help() | |
raise SystemExit() | |
if not options.access_key and 'AWS_ACCESS_KEY' in os.environ: | |
options.access_key = os.environ['AWS_ACCESS_KEY'] | |
if not options.secret_key and 'AWS_SECRET_KEY' in os.environ: | |
options.secret_key = os.environ['AWS_SECRET_KEY'] | |
if not options.secret_key or not options.access_key: | |
sys.stderr.write("ERROR: must supply both an access key " | |
"and secret key!\n") | |
parser.print_help() | |
raise SystemExit() | |
write_hosts(options.access_key, options.secret_key, \ | |
options.domain, options.output) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment