-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlambda_autoShutdown.py
executable file
·45 lines (35 loc) · 1.38 KB
/
lambda_autoShutdown.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
import boto3
# TODO: shift this to an environment variable?
dryRun = False
# TODO: re-code to search thru all regions
region = 'us-east-1'
# TODO: shift this to an environment variable?
ignoreTag = 'DoNotAutoShutdown'
# TODO: better error checking
def lambda_handler(event, context):
ec2 = boto3.resource('ec2')
ec = boto3.client('ec2')
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
stoplist = []
if dryRun:
print '+++dryRun enabled+++'
for instance in instances:
print instance.id + ': found instance (type ' + instance.instance_type + ')'
skipInstance = False
if instance.tags is None:
print instance.id + ': instance has no tags!'
else:
for t in instance.tags:
if t['Key'].lower() == ignoreTag.lower():
if t['Value'].lower() == 'true':
skipInstance = True
if skipInstance:
print instance.id + ': instance is marked as ' + ignoreTag
else:
stoplist.append(instance.id)
if dryRun:
print '+++ec.stop_instance: dryrun trigger for instances', stoplist
else:
print 'sending stop request for instances', stoplist
ec.stop_instances(InstanceIds=stoplist)
print '+++end of lambda function+++'