-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstop_ec2_sentry.py
More file actions
94 lines (82 loc) · 3.14 KB
/
stop_ec2_sentry.py
File metadata and controls
94 lines (82 loc) · 3.14 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
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
import os
import json
import logging
import boto3
import botocore
# logging
log = logging.getLogger()
log.setLevel(logging.INFO)
# global variables
SNS_TOPIC_ARN = os.environ.get("sns_topic_arn")
REGION = "eu-west-2"
ENVIRONMENT_TAG = os.environ.get("environment")
# instantiate boto3 clients
ec2_client = boto3.client('ec2', region_name=REGION)
sns_client = boto3.client('sns')
def lambda_handler(event, context):
ids, count = check_running_instances()
if ids:
if stop_running_instances(ids):
log.info("stop_instances: successful")
if send_notification(count):
log.info("SNS publish: successful")
return {
'statusCode': 200,
'body': json.dumps({'message': "Successful requests."})
}
log.info("SNS publish: an error occurred")
return {
'statusCode': 206,
'body': json.dumps({'error': "An error occurred in the SNS publish request."})
}
log.info("stop_instances: an error occurred")
if not send_notification(count, False):
return {
'statusCode': 500,
'body': json.dumps({'error': "An error occurred, all requests failed."})
}
return {
'statusCode': 206,
'body': json.dumps({'error': "An error occurred in the stop_instance request."})
}
log.info("describe_instances: an error occurred")
raise Exception("describe_instances could't find any instance ID's or not running instances found")
def check_running_instances():
filters = [
{'Name' : "tag:environment",'Values' : [ENVIRONMENT_TAG]},
{'Name' : "instance-state-name",'Values' : ['running']},
]
try:
response = ec2_client.describe_instances(Filters=filters)
instances_id = []
for instance in response['Reservations']:
instances_id.append(instance['Instances'][0]['InstanceId'])
count = len(instances_id)
return instances_id, count
except botocore.exceptions.ClientError as error:
log.error(f"Boto3 API returned error: {error}")
return False
def stop_running_instances(instances_id):
try:
ec2_client.stop_instances(InstanceIds=instances_id)
return True
except botocore.exceptions.ClientError as error:
log.error(f"Boto3 API returned error: {error}")
return False
def send_notification(count, success=True):
message = "Some requests have failed. The Lambda function couldn't perform the task.\n"
subject = "WARNING: Auto-Mitigation unsuccessful"
if success:
message = "The lambda function was triggered successfully.\n"
subject = "AUTO-MITIGATION: successfull"
message += (
f"{count} running instances found and stopped.\n"
f"Region: {REGION}\n"
f"Environment: {ENVIRONMENT_TAG}"
)
try:
sns_client.publish(TargetArn=SNS_TOPIC_ARN, Message=message, Subject=subject)
return True
except botocore.exceptions.ClientError as error:
log.error(f"Boto3 API returned error: {error}")
return False