-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAutostopec2instance.py
39 lines (30 loc) · 997 Bytes
/
Autostopec2instance.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
import boto3
import logging
#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)
#define the connection and set the region
ec2 = boto3.resource('ec2', region_name='ap-southeast-1')
def lambda_handler(event, context):
# all running EC2 instances.
filters = [{
'Name': 'tag:AutoStop',
'Values': ['True']
},
{
'Name': 'instance-state-name',
'Values': ['running']
}
]
#filter the instances which are stopped
instances = ec2.instances.filter(Filters=filters)
#locate all running instances
RunningInstances = [instance.id for instance in instances]
#print the instances for logging purposes
#print RunningInstances
if len(RunningInstances) > 0:
#perform the shutdown
shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).stop()
print(shuttingDown)
else:
print("Nothing to see here")