Member-only story
Schedule your EC2 instances to stop and start using Lambda(boto3) and Cloudwatch
Just take an example that you have a very large organization over 100 people and your instances are not being used after business hours but you are still paying for that unused time. It would be a very tiresome process to stop all the instances manually if it is spread across all the regions.
We can automate by following process:
- Create a Lambda Function with Python 3.7( I used this python version while implementing in my organization. Yours may have got updated but the code will be following python 3.7 rules. So follow accordingly),
- For roles, first create a policy in IAM by pasting the following code in JSON:
{
“Version”: “2012–10–17”,
“Statement”: [
{
“Effect”: “Allow”,
“Action”: [
“logs:CreateLogGroup”,
“logs:CreateLogStream”,
“logs:PutLogEvents”
],
“Resource”: “arn:aws:logs:*:*:*”
},
{
“Effect”: “Allow”,
“Action”: [
“ec2:DescribeInstances”,
“ec2:DescribeRegions”,
“ec2:StartInstances”,
“ec2:StopInstances”
],
“Resource”: “*”
}
]
}
Select this policy while creating Lambda Role. Select this role while creating your Lambda function. This roles allow the function to access Cloudwatch logs, events and EC2 instance( stop-start and to describe region in which the instance is present)