How to start and stop instances using lambda and Cloudwatch

Опубликовано: 17 Март 2026
на канале: Aviz Academy | AWS with Avinash Reddy
14,392
267

In this video tried to explain how to start / stop instance periodically or at given time using Lambda function and CloudWatch events.
Please find the required Role and Lambda Scrips
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:Start*",
"ec2:Stop*"
],
"Resource": "*"
}
]
}

Stops the EC2 instances
import boto3
region = 'ap-south-1'
instances = ['i-12345', 'i-2345']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=instances)
print('stopped your instances: ' + str(instances))

Starts the EC2 instances

import boto3
region = 'ap-south-1'
instances = ['i-12345', 'i-2345']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print('started your instances: ' + str(instances))