To automatically start or stop an EC2 instance using AWS Lambda and EventBridge (CloudWatch Events).
- AWS Account
- One running EC2 instance
- IAM Role with proper permissions
- Basic knowledge of AWS Lambda and IAM
Steps
- Go to IAM > Roles > Create role
Add Permission policy β Use JSON policy enabling EC2 start/stop and log access:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:StartInstances",
"ec2:StopInstances",
"ec2:DescribeInstances"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}
-
Lambda β Create Function β Author from scratch
-
Runtime: Python 3.x
-
Change Default execution role--use existing
-
Existing role -->select role name
-
Created functionβ
-
Use this code
-
π view Code
-
Delpoy it β
IMP- Edit the Instance id in that
- Test manually with
{}
- timeout
- 30 sec
- configured β
-
Go to EventBridge β Scheduler β Create schedule
-
Choose a cron expression (e.g., cron(0 3 * * ? *) for 3β―AM UTC)
-
π Explanation:
3 β minute (03)
11 β hour (11 AM UTC)
31 β day of month (31st)
7 β July
? β ignore day-of-week
2025 β year
Target: select relevant Lambda function
Pass custom payload like
{ "action": "start/stop" }
Created Function Rule - Update Rule β
- Go to configuration
- Add Trigers:
- EventBridge (CloudWatch Events): ec2-stop-rule
- EventBridge (CloudWatch Events): ec2-start-rule



