-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
53 lines (40 loc) · 1.58 KB
/
lambda_function.py
File metadata and controls
53 lines (40 loc) · 1.58 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
import boto3
import json
from botocore.exceptions import ClientError
def lambda_handler(event, context):
print ("Importing boto3 class for ec2 service")
# Boto Version Check
print(boto3.__version__)
#define the connection
client = boto3.resource('ec2')
# Get state
instanceState = event["instanceState"]
filters = event["tags"]
print(filters)
print(instanceState)
#filter the instances
instance_iterator = client.instances.filter(Filters=filters)
#Get IDs of all running and tagged instances
instance_ids = [instance.id for instance in instance_iterator]
#Print list of instances that will be stopped to logs
print("instances ids : " + ', '.join(instance_ids))
# Starting instances
if (len(instance_ids) > 0 and instanceState == "on"):
# Starting the instances
print ('Trying to Start the EC2 instances : ' + ', '.join(instance_ids))
try:
starting_instances = client.instances.filter(InstanceIds=instance_ids).start()
return starting_instances
except ClientError as e:
print(e)
# Stopping instances
if (len(instance_ids) > 0 and instanceState == "off"):
# Stopping the instances
print ('Trying to Stop EC2 instances : ' + ', '.join(instance_ids))
try:
stopping_instances = client.instances.filter(InstanceIds=instance_ids).stop()
return stopping_instances
except ClientError as e:
print(e)
# End
return "Script execution completed. See Cloudwatch logs for complete output"