-
Notifications
You must be signed in to change notification settings - Fork 15
/
aws_tool.py
executable file
·68 lines (57 loc) · 2.02 KB
/
aws_tool.py
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
#!/usr/bin/env python
# tool to automate various AWS commands
# TODO: transition to argparse
import boto3
import sys
import os
import time
from operator import itemgetter
import util as u
LIMIT_TO_KEY='nexus'
def list_instances():
print("Region", u.get_region())
ec2 = u.create_ec2_resource()
instances = [(u.seconds_from_datetime(i.launch_time), i) for i in ec2.instances.all()]
sorted_instances = sorted(instances, key=itemgetter(0))
for (seconds, instance) in sorted_instances:
hours_ago = (time.time()-seconds)/3600
hours_ago+=8 # adjust for time being in UTC
if instance.state['Name'] not in ('running', 'terminating'):
continue
if not (LIMIT_TO_KEY in instance.key_name):
continue
print("%4s %20s %10s %20s %s %s" %(int(hours_ago),
u.get_name(instance.tags), instance.instance_type,
instance.public_ip_address,
instance.private_ip_address,
instance.id
))
def get_instance(fragment):
ec2 = u.create_ec2_resource()
instances = [(u.seconds_from_datetime(i.launch_time), i) for i in ec2.instances.all()]
# latest instance first
sorted_instances = reversed(sorted(instances, key=itemgetter(0)))
for (seconds, instance) in sorted_instances:
name = u.get_name(instance.tags)
if fragment in u.get_name(instance.tags):
hours_ago = (time.time()-seconds)/3600
hours_ago+=8 # adjust for time being in UTC
print("Found instance %s launched %.1f hours ago" %(name, hours_ago,))
return instance
print("Found nothing matching", fragment)
def main():
if len(sys.argv) < 2:
mode = 'list'
else:
mode = sys.argv[1]
if mode == 'list' or mode == 'ls':
list_instances()
elif mode == 'reboot':
task_fragment = sys.argv[2]
instance = get_instance(task_fragment)
print("Rebooting "+u.get_name(instance.tags))
instance.reboot()
else:
assert False, "Unknown mode "+mode
if __name__=='__main__':
main()