Day 23–101 Days of DevOps — How to stop/start EC2 instances on a scheduled basis to save cost using AWS Lambda and CloudWatch

Go to IAM Console https://console.aws.amazon.com/iam/home?region=us-west-2#/home --> Roles --> Create role
{
"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 Author from scratch
* Name: Give your Lambda function any name
* Runtime: Select Python3.8 as runtime
* Role: Choose the role we create in first step
* Click on Create function
import boto3

def lambda_handler(event, context):
ec2 = boto3.resource("ec2")

regions = []
for region in ec2.meta.client.describe_regions()['Regions']:
regions.append(region['RegionName'])

for region in regions:
ec2 = boto3.resource("ec2", region_name=region)

print("EC2 region is: ", region)

ec2_instance = {"Name": "instance-state-name", "Values": ["running"]}

instances = ec2.instances.filter(Filters=[ec2_instance])

for instance in instances:
instance.stop()
print("The following EC2 instances is now in stopped state", instance.id)
* Under Cron expression choose * 18 * * ? * (If you want to shutdown your instance at 6pm everyday)
* Choose Add target, and then choose Lambda function that you created earlier to stop the instance
* Only difference is different time schedule
* Under target different Lambda function(to start the instance)
Lambda function --> Monitoring --> View logs in CloudWatch

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Prashant Lakhera

Prashant Lakhera

4.91K Followers

AWS Community Builder, Ex-Redhat, Author, Blogger, YouTuber, RHCA, RHCDS, RHCE, Docker Certified,4XAWS, CCNA, MCP, Certified Jenkins, Terraform Certified, 1XGCP