Select your cookie preferences

We use essential cookies and similar tools that are necessary to provide our site and services. We use performance cookies to collect anonymous statistics, so we can understand how customers use our site and make improvements. Essential cookies cannot be deactivated, but you can choose “Customize” or “Decline” to decline performance cookies.

If you agree, AWS and approved third parties will also use cookies to provide useful site features, remember your preferences, and display relevant content, including relevant advertising. To accept or decline all non-essential cookies, choose “Accept” or “Decline.” To make more detailed choices, choose “Customize.”

AWS Logo
Menu
Automatically Stopping an EC2 Instance Using AWS Lambda and EventBridge

Automatically Stopping an EC2 Instance Using AWS Lambda and EventBridge

Automating the stopping of AWS EC2 instances can help optimize your costs and resource utilization. This guide will walk you through creating an automation workflow using AWS Lambda and Amazon EventBridge.

Published Nov 16, 2024
Last Modified Nov 18, 2024
Step 1: Create 2 EC2 instances, selecting any operating system and instance type you prefer. Additionally, make sure to note down the two instance IDs.
Image not found
Step 2: Create a Lambda function, selecting Python 3.9 as the runtime and arm64 as the architecture.
Image not found
Step 3: Go to Code Source section and replace the existing code. Make sure add previously saved instances ids and your region. In my case used us-east-2. Code
Image not found
Step 4: To add permission to manage EC2, go to the Configuration section and click on the Permissions tab. Then, redirect to the IAM role. After that, add the EC2 FullAccess role.
Image not found
Image not found
Image not found
Step 5: Go to the Test tab and create a test event. Then, click the Test button to run it.
Image not found
You will see the following response, indicating that your EC2 instance has stopped.
Image not found
Step 6: In the Lambda function, click the "Add Trigger" button and select EventBridge as the trigger.
Image not found
Then, choose "Create a new rule." Next, select the schedule expression and provide the cron expression. Please ensure the time conversion works in UTC, as you need to convert the time for the schedule. For example, I converted UTC time to IST. Ref: CronTab
Image not found
Finally, you will see that your EC2 instances have been stopped.
Image not found
Clean Up
  • Terminate EC2 Instances
  • Remove Lambda Function
Thanks for reading the Article.
 

Comments

Log in to comment