PageRenderTime 18ms CodeModel.GetById 15ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms

/boto-2.5.2/bin/list_instances

#
#! | 73 lines | 60 code | 13 blank | 0 comment | 0 complexity | 42d3c739a0b12e92d91d46191a9d3350 MD5 | raw file
 1#!/usr/bin/env python
 2
 3import sys
 4from operator import attrgetter
 5from optparse import OptionParser
 6
 7import boto
 8from boto.ec2 import regions
 9
10
11HEADERS = {
12    'ID': {'get': attrgetter('id'), 'length':15},
13    'Zone': {'get': attrgetter('placement'), 'length':15},
14    'Groups': {'get': attrgetter('groups'), 'length':30},
15    'Hostname': {'get': attrgetter('public_dns_name'), 'length':50},
16    'State': {'get': attrgetter('state'), 'length':15},
17    'Image': {'get': attrgetter('image_id'), 'length':15},
18    'Type': {'get': attrgetter('instance_type'), 'length':15},
19    'IP': {'get': attrgetter('ip_address'), 'length':16},
20    'PrivateIP': {'get': attrgetter('private_ip_address'), 'length':16},
21    'Key': {'get': attrgetter('key_name'), 'length':25},
22    'T:': {'length': 30},
23}
24
25def get_column(name, instance=None):
26    if name.startswith('T:'):
27        _, tag = name.split(':', 1)
28        return instance.tags.get(tag, '')
29    return HEADERS[name]['get'](instance)
30
31
32def main():
33    parser = OptionParser()
34    parser.add_option("-r", "--region", help="Region (default us-east-1)", dest="region", default="us-east-1")
35    parser.add_option("-H", "--headers", help="Set headers (use 'T:tagname' for including tags)", default=None, action="store", dest="headers", metavar="ID,Zone,Groups,Hostname,State,T:Name")
36    (options, args) = parser.parse_args()
37
38    # Connect the region
39    for r in regions():
40        if r.name == options.region:
41            region = r
42            break
43    else:
44        print "Region %s not found." % options.region
45        sys.exit(1)
46    ec2 = boto.connect_ec2(region=region)
47
48    # Read headers
49    if options.headers:
50        headers = tuple(options.headers.split(','))
51    else:
52        headers = ("ID", 'Zone', "Groups", "Hostname")
53
54    # Create format string
55    format_string = ""
56    for h in headers:
57        if h.startswith('T:'):
58            format_string += "%%-%ds" % HEADERS['T:']['length']
59        else:
60            format_string += "%%-%ds" % HEADERS[h]['length']
61
62
63    # List and print
64    print format_string % headers
65    print "-" * len(format_string % headers)
66    for r in ec2.get_all_instances():
67        groups = [g.name for g in r.groups]
68        for i in r.instances:
69            i.groups = ','.join(groups)
70            print format_string % tuple(get_column(h, i) for h in headers)
71
72if __name__ == "__main__":
73    main()