forked from cloudacademy/lexstartstopinstances
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda.py
97 lines (66 loc) · 2.88 KB
/
lambda.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import boto3
import logging
import os
logger = logging.getLogger()
logger.setLevel(logging.INFO)
AWS_REGION = os.environ['INSTANCE_REGION']
INTENT_START_INSTANCES = 'StartInstances'
INTENT_STOP_INSTANCES = 'StopInstances'
def lambda_handler(event, context):
logger.info('event.bot.name={}'.format(event['bot']['name']))
return dispatch(event)
def dispatch(intent_request):
intent_name = intent_request['currentIntent']['name']
if intent_name == INTENT_START_INSTANCES:
return ec2_instances_start(intent_request)
elif intent_name == INTENT_STOP_INSTANCES:
return ec2_instances_stop(intent_request)
raise Exception('Lex Intent with name {} not supported'.format(intent_name))
def ec2_instances_start(intent_request):
logger.info("ec2_instances_start entered...")
logger.info(intent_request)
instance_tag = intent_request['currentIntent']['slots']['serverType']
try:
ec2 = boto3.client('ec2', region_name=AWS_REGION)
filters = [{'Name': 'tag:Type', 'Values': [instance_tag]}]
response = ec2.describe_instances(Filters=filters)
instance_ids = []
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
instance_ids.append(instance["InstanceId"])
ec2.start_instances(InstanceIds=instance_ids)
message = "EC2 instances with tag {} were STARTED successfully!".format(instance_tag)
except BaseException as e:
message = "A problem was encountered trying to START the {} EC2 instances".format(instance_tag)
logger.error('ec2_instances_start, error={}'.format(str(e)))
return close(message)
def ec2_instances_stop(intent_request):
logger.info("ec2_instances_stop entered...")
logger.info(intent_request)
instance_tag = intent_request['currentIntent']['slots']['serverType']
try:
ec2 = boto3.client('ec2', region_name=AWS_REGION)
filters = [{'Name': 'tag:Type', 'Values': [instance_tag]}]
response = ec2.describe_instances(Filters=filters)
instance_ids = []
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
instance_ids.append(instance["InstanceId"])
ec2.stop_instances(InstanceIds=instance_ids)
message = "EC2 instances with tag {} were STOPPED successfully!".format(instance_tag)
except BaseException as e:
message = "A problem was encountered trying to STOP the {} EC2 instances.".format(instance_tag)
logger.error('ec2_instances_stop, error={}'.format(str(e)))
return close(message)
def close(message):
response = {
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText",
"content": message
}
}
}
return response