-
Notifications
You must be signed in to change notification settings - Fork 0
/
lsec2
executable file
·87 lines (67 loc) · 2.4 KB
/
lsec2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/python
#
# List EC2 Instances
#
# Boto3 Documentation
# http://boto3.readthedocs.io/en/latest/reference/services/ec2.html
#
import boto3
import datetime
import getopt
import os
import sys
import tabulate
import time
def usage():
print('Usage: lsec2 [-p <profile>]')
def ec2InstanceName(instance):
if instance is not None and hasattr(instance, 'tags') and instance.tags is not None:
for tag in instance.tags:
key = tag.get('Key', '_')
if key == 'Name':
return tag.get('Value', '?')
return 'No-Name'
def ec2Age(instance):
tz = instance.launch_time.tzinfo
diff = datetime.datetime.now(tz) - instance.launch_time
# timedelta string looks like "55 days, 1:25:48.111432"
# chop off the milliseconds
return str(diff).split('.', 1)[0]
def ec2AvailabilityZone(instance):
return instance.placement['AvailabilityZone']
def main():
# command line options
profile = os.getenv('AWS_PROFILE', 'default')
try:
opts, args = getopt.getopt(sys.argv[1:],'hp:',['profile='])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
usage()
sys.exit(2)
elif opt in ('-p', '--profile'):
profile = arg
# open session to AWS EC2
# will raise ProfileNotFound exception if profile name not found
session = boto3.Session(profile_name=profile)
ec2 = session.resource('ec2')
# get list of instances
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
output = []
for instance in instances:
name = ec2InstanceName(instance)
az = ec2AvailabilityZone(instance)
age = ec2Age(instance)
output.append( [ name, instance.public_ip_address, instance.id, instance.instance_type, az, age ] )
output = sorted(output, key=lambda k: (k[0], k[2]))
headers = ['Name', 'Public IP', 'ID', 'Type', 'AZ', 'Age']
print(tabulate.tabulate(output, headers=headers, tablefmt='plain'))
# if tabulate is not installed, use this to display results:
#outputformat = '{: <25} {: <16} {: <20} {: <10} {: <10} {}'
#print(outputformat.format(headers[0], headers[1], headers[2], headers[3], headers[4], headers[5]))
#for row in output:
# print(outputformat.format(row[0], row[1], row[2], row[3], row[4], row[5]))
main()
exit