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

  • One of the major challenges in implementing this will be if the Developer is working late and wants his instance to be run beyond 6 pm or an urgent patch he needs to implement and need to work on the weekend?
  • One common solution we come out with is manually specifying the list of an instance in Python Code(Lambda Function), and in case of exception it goes through a change management process where we need to remove developer instance manually(Agree is not an ideal solution but so far works great)
Go to IAM Console https://console.aws.amazon.com/iam/home?region=us-west-2#/home --> Roles --> Create role
  • In the next screen, select Create Policy; IAM Policy will look like this
{
"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": "*"
}
]
}
  • Add this newly created policy to the role
* 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
  • In this scenario, we need to create Function one to stop an instance and others to start an instance.
  • To stop an instance, the code will look like this. We already discussed this code on Day 17.
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
  • The same steps need to be repeated for Starting the instance(rather than using instance.stop() you need to use instance.start(), and during filtering, the value should be stopped.
* Only difference is different time schedule
* Under target different Lambda function(to start the instance)
  • Once the event is triggered, go to your
Lambda function --> Monitoring --> View logs in CloudWatch
  • For stopping the instance, you will see something like this.
  • For starting the instance
  • The simple automation system is ready to stop/start the instance and to save some company money.

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why is Salesforce booming in the last few years?

salesforce PD1

Why We Use Scrum Methodology

Building a Mobile Graph-Powered Login and Signup System using Flutter, TigerGraph, and Fast API

IoTPi 4 & 6 Channel Industrial IoT board based on RP2040 @Raspberry_Pi #RaspberryPi

5 Best Tool for Event Planner

FPB 2 Weeks Bootcamp Report

AWS Solution Architect Associate SAA-C02: Part 11 - High Availability.

For loops in Python

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

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

More from Medium

What is AWS Elastic Beanstalk

Cloud Platforms like AWS and more….!!!!!

AWS SysOps Certification Exam Gets an Update

What’s New With SAA-C03 AWS Certified Solutions Architect Associate exam?