-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaws-new.py
More file actions
93 lines (82 loc) · 2.85 KB
/
Copy pathaws-new.py
File metadata and controls
93 lines (82 loc) · 2.85 KB
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
88
89
90
91
92
93
import boto3
import sys
import time
def get_credentials():
with open("aws.keys", 'r') as fh:
return fh.readlines()
cred = get_credentials()
auth = {"aws_access_key_id": cred[0].strip('\n'), "aws_secret_access_key": cred[1].strip('\n')}
def main():
if len(sys.argv) < 2:
print("Usage: python aws.py {start|stop|info}\n")
sys.exit(0)
else:
action = sys.argv[1]
try:
#ec2 = boto.ec2.connect_to_region("ap-south-1", **auth)
ec2 = boto3.client("ec2", "ap-south-1", **auth)
except Exception as e1:
error1 = "Error1: %s" % str(e1)
print(error1)
sys.exit(0)
if action == "start":
startInstance(ec2)
elif action == "stop":
stopInstance(ec2)
elif action == 'info':
get_details(ec2)
else:
startInstance(ec2, action)
#print "Usage: python aws.py {start|stop}\n"
def get_instance_ids(ec2):
response = ec2.describe_instances()
instances = [i for r in response['Reservations'] for i in r['Instances']]
print([instance['InstanceId'] for instance in instances])
return [instance['InstanceId'] for instance in instances]
#ids = []
#with open('/home/gbhure/aws.txt') as fd:
#for instance in fd:
#ids.append(instance.split(':')[0])
#return ids
import json
def get_details(ec2):
response = ec2.describe_instances()
instances = [i for r in response['Reservations'] for i in r['Instances']]
instance_ids = []
print('Node\t\tID\t\tStatus')
for instance in instances:
if instance.get('PublicIpAddress'):
print(instance['Tags'][0]['Value'] + " : " + instance['InstanceId'] + " : " + instance['PublicIpAddress'])
else:
print(instance['Tags'][0]['Value'] + " : " + instance['InstanceId'] + " : " + 'Down')
#instance_ids.append(str(instance).split(':')[1])
print("")
print(instance_ids)
return(instance_ids)
def startInstance(ec2, id=None):
if isinstance(id, str):
print("Starting the instance...", id)
ec2.start_instances(instance_ids=[id])
time.sleep(20)
else:
print("Starting the instance...", get_instance_ids(ec2))
try:
try:
ec2.start_instances(InstanceIds=get_instance_ids(ec2))
except Exception:
print('Something went wrong, check if all instances started..')
time.sleep(20)
except Exception as e2:
error2 = "Error2: %s" % str(e2)
print(error2)
sys.exit(0)
get_details(ec2)
def stopInstance(ec2):
print("Stopping the instance...", get_instance_ids(ec2))
try:
ec2.stop_instances(InstanceIds=get_instance_ids(ec2))
time.sleep(20)
except Exception:
print('Something went wrong, check if all instances stopped..')
if __name__ == '__main__':
main()