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.
Step 2: Create a Lambda function, selecting Python 3.9 as the runtime and arm64 as the architecture.
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
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.
Step 5: Go to the Test tab and create a test event. Then, click the Test button to run it.
You will see the following response, indicating that your EC2 instance has stopped.
Step 6: In the Lambda function, click the "Add Trigger" button and select EventBridge as the trigger.
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
Finally, you will see that your EC2 instances have been stopped.
Clean Up
  • Terminate EC2 Instances
  • Remove Lambda Function
Thanks for reading the Article.
 

Comments