· 7 years ago · Nov 24, 2018, 08:54 AM
1import sys
2import os
3import boto
4
5from optparse import OptionParser
6from contextlib import closing
7
8parser = OptionParser()
9parser.add_option('-a', '--access-key', default=None, dest='access_key',
10 help="AWS access key (required)")
11parser.add_option('-d', '--domain', default=None, dest='domain',
12 help="Top-level domain")
13parser.add_option('-s', '--secret-key', default=None, dest='secret_key',
14 help="AWS secret key (required)")
15parser.add_option('-o', '--output', default=None, dest='output',
16 help="Output file (defaults to stdout)")
17
18def open_output(f):
19 if f == None or f == '-':
20 fd = sys.stdout.fileno()
21 return os.fdopen(fd, 'w')
22 else:
23 return open(f, 'w')
24
25def write_hosts(access, secret, domain, output):
26 conn = boto.connect_ec2(access, secret)
27 instances = conn.get_all_instances()
28 fmt = ''
29 if domain:
30 fmt = '%(ip)s %(name)s.int %(name)s.int.%(domain)s'
31 else:
32 fmt = '%(ip)s %(name)s.int'
33
34 lines = ['127.0.0.1 localhost localhost.localdomain']
35 for ins in instances:
36 for i in ins.instances:
37 if i.state == 'running' and 'Name' in i.tags:
38 if len(i.tags['Name']) == 0:
39 continue
40
41 lines.append(fmt % {'ip': i.private_ip_address,
42 'name': i.tags['Name'],
43 'domain': domain})
44 if len(lines) > 1:
45 with closing(open_output(output)) as out:
46 out.write('\n'.join(lines))
47 out.write('\n')
48 return True
49 return False
50
51if __name__ == '__main__':
52 (options, args) = parser.parse_args()
53 output = None
54
55 if len(args) > 0:
56 sys.stderr.write("ERROR: no extra args needed!\n")
57 parser.print_help()
58 raise SystemExit()
59
60 if not options.access_key and 'AWS_ACCESS_KEY' in os.environ:
61 options.access_key = os.environ['AWS_ACCESS_KEY']
62
63 if not options.secret_key and 'AWS_SECRET_KEY' in os.environ:
64 options.secret_key = os.environ['AWS_SECRET_KEY']
65
66 if not options.secret_key or not options.access_key:
67 sys.stderr.write("ERROR: must supply both an access key "
68 "and secret key!\n")
69 parser.print_help()
70 raise SystemExit()
71
72 write_hosts(options.access_key, options.secret_key, \
73 options.domain, options.output)