Start and Stop Ec2 Instances with CloudWatch Event rule and Lambda
This note can be usefull for those of you who needs to hav EC2 instance running during the certain period of time during the day and awoid spending money when the instance is not needed. I use the bmwitcher.medium.com article but with a small changes:
- There is only one lambda function
- The cloudwatch event rules have custom contraint in json format to be forwarded as event to the lambda
Steps are the following
- Create lambda function with the code specified below
import boto3 region = 'us-east-1' ec2 = boto3.client('ec2', region_name=region) def lambda_handler(event, context): if event["action"] == "stop": ec2.stop_instances(InstanceIds=[event["instance_id"]]) if event["action"] == "start": ec2.start_instances(InstanceIds=[event["instance_id"]])
- Create the following IAM policy
{ "Version": "2012-10-17", "Statement": [ { "Action": [ "ec2:DescribeInstances" ], "Resource": [ "*" ], "Effect": "Allow", "Condition": {} }, { "Action": [ "ec2:StartInstances", "ec2:StopInstances" ], "Resource": [ "arn:aws:ec2:::instance/*" ], "Effect": "Allow", "Condition": {} } ] }
-
Attach this policy to the lambda execution IAM role. The role name can be found on the lambda configuration tab
- Create 2 separarte CloudWatch rules to stop and start instances at the spcified schedule