Automatically Stop/Start EC2 instances using AWS Lambda| CloudWatch Events Scheduler

Automatically Stop/Start EC2 instances using AWS Lambda| CloudWatch Events Scheduler

Create a policy

Log in to the AWS console and navigate to IAM > policies > Create policy

Select EC2 and click on write

Under write, select StartInstances and StopInstances

Under resources tab click on Add Arn

Start providing the region, instance Id, and ARN will be autogenerated

Provide the policy name and click on create

Policy is created

Create an IAM role

Now navigate to roles > create roles > AWS service > Use case Lambda

Attach the policy that we created to it and create a role

Create Lambda functions for EC2 Start and Stop

Lambda > Create function

Use the role that we have created for the execution role and click on create function

A function named start is created

Click on the code, replace the code with below and deploy it to save

import boto3
region = 'ap-south-1'                  #Add your own region
instances = ['i-0662bece5ceee3edf']    #Add your own instance
ec2 = boto3.client('ec2', region_name=region)

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

It looks like below

Click on Test and Configure test event

Click on Create new event and provide the name and save it.

now click on Test to run the script

Check the execution result and the instance stated successfully

An instance started running successfully

In the same way, you can stop the instance by creating another lambda function

import boto3
region = 'ap-south-1'                  #Add your own region
instances = ['i-0662bece5ceee3edf']    #Add your own instance
ec2 = boto3.client('ec2', region_name=region)

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

I have created 2 lambda functions for start and stop

Schedule to start/stop the EC2 instance in Cloud Watch using crobtab

Navigate to Cloudwatch > Events > Rules > Create a Rule

Provide the name and select it as schedule because as our EC2 is already running we will stop the EC2 instance based on scheduled timings.

Click on Continue in EventBridge Scheduler

Select it as a recurring schedule and provide the time in cron expression box

keep the flexible time window as off

Select target will be Templated targets > AWS lambda invoke

Under Invoke, select the stop lambda function that we created to stop the instance

Leave the rest to defaults and click on create schedule

Instance is stopped

Create another schedule to start the instance in cloud watch using the lambda function.