Automate Start-Stop EC2 Instances Using Lambda

Aruzhan Abduvali
AWS Tip
Published in
2 min readMay 8, 2024

--

Introduction

This guide will walk you through the process of automating the starting and stopping of EC2 instances using an AWS Lambda function. By implementing this function, you can effectively manage your EC2 instances, save costs, and schedule operations according to your requirements using cron jobs.

Step 1: Create an EC2 Instance

To begin, you’ll need to create a simple EC2 instance on AWS. Ensure that you have necessary permissions to create and manage EC2 instances.

Step 2: Create an IAM Policy

Create an IAM policy that grants permissions for starting and stopping EC2 instances. Below is an example policy:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ec2:StartInstances",
"ec2:StopInstances"
],
"Resource": "arn:aws:ec2:*:123456789:instance/*"
}
]
}

Ensure to replace 123456789 with your AWS account ID.

Step 3: Create an IAM Role

Create an IAM role for Lambda with the necessary permissions. Attach the IAM policy created in Step 2 to this role.

Step 4: Create a Lambda Function

Create a Lambda function using Python 3.9. You can use the official AWS documentation, which provides ready-to-use Python code for starting and stopping EC2 instances.

Stop and start EC2 instances at intervals with Lambda function | AWS re:Post (repost.aws)

Step 5: Add a Trigger

Add a trigger to your Lambda function using Amazon EventBridge (CloudWatch Events). Configure the trigger with a cron expression to define the schedule for starting and stopping EC2 instances.

You can use the following configuration as a reference:

If you encounter difficulties creating your cron job, refer to the official AWS documentation for detailed instructions.

Conclusion

By following these steps, you can automate the management of your EC2 instances using Lambda functions and EventBridge. This setup allows you to optimize costs and efficiently schedule operations according to your specific requirements.

--

--