Automatically start and stop ec2 instance using Lambda

Automate EC2 instances in AWS to manage costs effectively and ensure optimized resource usage. With AWS Lambda, you can set up scheduled start and stop times for EC2 instances, making it easy to align usage with peak and off-peak hours. This guide walks you through setting up automation for EC2, from IAM role creation to CloudWatch event rules.If you have off-peak hours in your business, you can configure AWS to automatically stop your instances during these wee hours and start them back during your peak hours! 

How to Automate EC2 Instances with AWS Lambda

What happens when you stop and start an Instance at a fixed interval?

  • Once you shutdown an instance, you will no longer pay for the compute charges. They only charge for the storage for any Amazon EBS volumes attached to that instance.
  • If your instances use EBS volumes, data persists over restarts.
  • Elastic IP and Private addresses are retained when instances are restarted.

Following steps help you to automate the stopping & starting of your AWS EC2 instances:

  1. IAM roles for Lambda functions.
  2. AWS Lambda functions
  3. Cloudwatch Events
  4. Tagging your AWS resources.

1) IAM Role for AWS Lambda

A Lambda function requires an execution role created in IAM that provides the function that we create with the necessary permissions to run. 

IAM Role enables:

  • Lambda to access the EC2 Instances with permission to Stop & Start instances.
  • Access to Cloudwatch to write logs.

Navigate to IAM, the click on Roles and Create new role (say ec2_start_stop)

Please use Json Editor and paste the below inline policy content:

{

    “Version”: “2012-10-17”,

    “Statement”: [

        {

            “Sid”: “VisualEditor0”,

            “Effect”: “Allow”,

            “Action”: [

                “logs:CreateLogStream”,

                “ec2:DescribeInstances”,

                “ec2:StartInstances”,

                “ec2:StopInstances”,

                “logs:CreateLogGroup”,

                “logs:PutLogEvents”

            ],

            “Resource”: “*”

        }

    ]

}

how to Automatically start and stop ec2 instance using Lambda

2) AWS Lambda Function:

Lets create a Lambda function, say “ec2_start_stop”.

  • When you create Lambda function, use Node.js 8.10 or above
  • Select the IAM role previously created “ ec2_start_stop”.
  • Copy the Lambda code and after that paste in your Lambda function and save it.

https://git.spiralbean.com/-/snippets/1/raw

3) Cloud Watch Events:

CloudWatch Event rules will help us trigger the Lambda functions we created in the step (2). We will use the Schedule policy in the Cloudwatch Event rule to achieve this.

a) Create Cloudwatch Event rule for Starting the Instance:

  • Create a rule “ec2_start”
  • In the Event Source, Select Schedule (Cron Job)
  • In the cron expression, type “00 5 * * ? *”  (To start the instance at 5 am). Cron expressions specify when you want to stop your instances. The above cron runs every day at 5 am.
  • Add Lambda Trigger in the target panel. Select the Lambda function “ec2_start_stop”
  • Configure input with JSON text. 
  • Constant (JSON text): {“action”: “start”}

This cloudwatch event is triggered every day at 5 am and executes the lambda function.

cloudwatch rule creation

b) Create CloudWatch Event rules for Stopping the Instance:

  • Create Rule “ec2_stop
  • In the Event Source, Select Schedule,
  • In the cron expression, type “00 23* * ? *”  (To stop the instance at 11 pm). Cron expressions specify when you want to stop your instances.
  • Add Lambda Trigger in the target panel. Select the Lambda function “ec2_start_stop
  • Configure input with JSON text.

Constant (JSON text): {“action”: “stop”}

This cloudwatch event is triggered every day at 11pm and executes the lambda function.

triggering a AWS ncloudwatch event

The time zone is GMT and you will need to adjust to get the cron run in your time.

4) Tag your instances:

This is as important as the above steps. To implement this automation on EC2 instances, you will have to add a tag in your instances. Tag key is autostartstop and the tag value is true

Lambda scripts when executed look for these tags in the EC2 instances and only apply when these tags are true.

Great! You can sit back and see your instances shutdown automatically and come up on the scheduled interval.

GET STARTED WITH OUR CLOUD SERVICES

Vipin Venu

Technical Director at Activelobby, Cloud, DevOps & Micro-services Consultant

You may also like...

Leave a Reply