-
Notifications
You must be signed in to change notification settings - Fork 0
/
terminateinstances.py
executable file
·73 lines (66 loc) · 2.04 KB
/
terminateinstances.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
69
70
71
72
73
"""
terminate all instances not in allowed_instances.yaml file
"""
from __future__ import print_function, unicode_literals
import sys
import os
from os import path
from os.path import join
import os.path
import yaml
import json
import subprocess
conf_dir = sys.argv[1]
script_dir = path.dirname(path.realpath(__file__))
# print('script_dir', script_dir)
aws_path = sys.executable.replace('python', 'aws')
with open(join(conf_dir, 'allowed_instances.yaml'), 'r') as f:
allowed_instances = set(yaml.load(f))
# print('allowed_instances', allowed_instances)
regions = [
'us-west-1',
'us-west-2',
'us-east-1',
'eu-west-1',
'sa-east-1',
'ap-northeast-1',
'ap-southeast-1',
'ap-southeast-2',
]
# print('regions', regions)
instances = []
for region in regions:
# print('region', region)
contents = subprocess.check_output([
aws_path,
'--region', region,
'ec2',
'describe-instances',
'--filters', 'Name=instance-state-code,Values=16'
])
data = json.loads(contents)
for res in data['Reservations']:
for inst in res['Instances']:
if inst.get('InstanceLifecycle', '') == 'spot':
continue
instanceId = str(inst['InstanceId'])
if instanceId not in allowed_instances:
try:
print('stopping', instanceId)
print(subprocess.check_output([
aws_path,
'--region', region,
'ec2',
'stop-instances',
'--instance-ids', instanceId
]))
print('terminating', instanceId)
print(subprocess.check_output([
aws_path,
'--region', region,
'ec2',
'terminate-instances',
'--instance-ids', instanceId
]))
except Exception as e:
print('exception: ', e)