Last active
August 26, 2022 10:08
-
-
Save Kelvinskell/f3b8270b88722054edefb43e1451e431 to your computer and use it in GitHub Desktop.
An AWS lambda_function that will stop running ec2 instances when triggered.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import boto3 | |
import logging | |
from botocore.exceptions import ClientError | |
ec2 = boto3.client('ec2') | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
send_sns = False | |
def lambda_handler(event, context): | |
global send_sns | |
logger.info('Function {} has started execution.'.format(context.function_name)) | |
# Collect Instance ids for running instances | |
response = ec2.describe_instances() | |
ids = [] | |
for i in response['Reservations']: | |
if i['Instances'][0]['State']['Name'] == 'running': | |
ids.append(i['Instances'][0]['InstanceId']) | |
# Stop running instances | |
if ids: | |
try: | |
ec2.stop_instances(InstanceIds=ids, DryRun=False) | |
logger.info('Function {} has successfully executed.'.format(context.function_name)) | |
send_sns = True | |
except ClientError as e: | |
logger.info('Function {} has failed.'.format(context.function_name)) | |
print(e) | |
else: | |
logger.info('function {} could not find any running instances.'.format(context.function_name)) | |
# Send SNS Email | |
if send_sns: | |
sns = boto3.client('sns') | |
arn = 'YOUR SNS ARN' | |
notification = f'{len(ids)} of your EC2 instances with the following Instance ids have been successfully shutdown: {ids}' | |
response = sns.publish( | |
TargetArn=arn, | |
Message=json.dumps({'default': notification}), | |
MessageStructure='json' | |
) | |
return { | |
'statusCode': 200, | |
'body': json.dumps(response) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment