Schedule EC2 Shutdown with Lambda and CloudWatch
Introduction
In this technology era we are always concerned about reducing the cost whether its CAPex or OPex related. Running EC2 instances 24/7 when they’re not in use can lead to unnecessary costs, especially in development and testing environments. Fortunately, AWS offers a way to automate shutdowns using Lambda functions and CloudWatch Event Rules (now known as EventBridge).
In this guide, you’ll learn how to schedule automatic EC2 shutdowns every day using a simple Python Lambda function and a CloudWatch cron rule.
Prerequisites
Before we begin, make sure you have:
- An AWS account
- An existing EC2 instance you want to shut down automatically
- Permissions to create Lambda functions, IAM roles, and CloudWatch rules
Step 1: Create IAM Role
- Go to IAM.
- Navigate to Policy.
- Click on Create Policy.
![AWS Policy]](createpolicy.png)
- Paste the following JSON and click Next.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ec2:StopInstances",
"Resource": "*"
}
]
}
- Add the Policy Name and Description and Click on Create Policy.
- Click on Roles and then Create Role.
- Select Trusted Entity as AWS Service and Select Service as Lambda.
-
Select the Policy which is created in Step 5.
-
Add the Role Name and Click on Create.
Step 1: Create the Lambda Function
- Go to AWS Lambda Console
- Click Create function
- Choose:
- Author from scratch
- Runtime: Python 3.x
- Select the Role created in Execution Role
- Paste the following code and Click on Deploy:
import boto3
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
ec2.stop_instances(InstanceIds=['i-xxxxxxxxxxxxxxxxx']) # Replace with your EC2 instance ID
print("EC2 instance stopped")
Step 3: Create a CloudWatch Rule to Trigger Lambda
- Go to Amazon EventBridge (CloudWatch Events)
-
Click Rules > Create rule
-
Choose Schedule
-
Use cron expression: cron(0 22 * * ? *) → 10:00 PM UTC daily
-
As a target, select your Lambda function
-
Click Create
Step 4: Test Your Setup
You can test your automation by:
-
Manually triggering the Lambda function
-
Checking logs in CloudWatch Logs
-
Verifying that the EC2 instance changes to “stopped” state
Conclusion
By using AWS Lambda and CloudWatch Events, you can easily schedule EC2 shutdowns and reduce unnecessary cloud costs. This solution is simple, serverless, and scalable for multiple instances.