-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstop_all.py
41 lines (33 loc) · 1.28 KB
/
stop_all.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
import os
import botocore.session
import sys
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_DEFAULT_REGION = os.environ['AWS_DEFAULT_REGION']
def main():
session = botocore.session.Session()
session.set_credentials(AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY)
ec2 = session.get_service('ec2')
endpoint = ec2.get_endpoint(AWS_DEFAULT_REGION)
op_din = ec2.get_operation('DescribeInstances')
op_stop = ec2.get_operation('StopInstances')
http_response, reservation_data = op_din.call(endpoint, filters=[{"Name":"instance-state-name","Values":["running"]}] )
if not http_response.ok:
print(reservation_data['Errors'])
sys.exit(2)
else:
reservations = reservation_data['Reservations']
#Pull the instances out of reservations
instances = []
for reservation in reservations:
instances += reservation['Instances']
print("Found %i instances in running state" % len(instances))
instance_ids = [instance['InstanceId'] for instance in instances]
http_response, data = op_stop.call(endpoint, instance_ids = instance_ids)
if not http_response.ok:
print(data['Errors'])
sys.exit(2)
for instance in data['StoppingInstances']:
print("Instance %s now stopping" % instance['InstanceId'])
if __name__ == '__main__':
main()