AWS Lambda (Automatically Stopping EC2 Instances With AWS Lambda and EventBridge)

🚀 Introduction
Managing cloud costs efficiently is crucial for businesses, especially those with dynamic workloads. One of the simplest ways to optimize AWS spending is by automatically stopping EC2 instances during off-hours or non-peak times. Manual intervention for this task can be challenging, especially in large environments, leading to unnecessary costs and operational overhead. By automating the shutdown process using AWS Lambda and EventBridge, organizations can ensure resources are only active when needed, reducing wasted spend and freeing up technical teams for more valuable tasks. Additionally, automating these processes minimizes human error, creating a consistent and reliable shutdown schedule that aligns with business needs.
🔸Overview
A quick overview of how the automation will work:
Create a Lambda function.
Write Lambda code using Boto3 to interact with EC2.
Configure permissions to allow the Lambda function to stop EC2 instances.(create policy and attach to role)
Set up an EventBridge Rule to automatically stop EC2 instances at midnight.
Test the Lambda function to ensure it works correctly.
🔸What is Serverless Computing
Serverless Computing enables you to build and run application without worrying about servers, as the server on which it’s running is fully managed, provisioned, and scaled by AWS.
Scale with usage.
No server to provision or manage.
Never pay for idleness.
Fewer components.
🔸What is AWS Lambda
You can use AWS Lambda to run code without provisioning or managing servers, it means that you don’t have to worry about the infrastructure needed to run your application or script, it all handled by AWS automatically, You just upload your code, configure when it should run, and AWS runs it for you on demand, this is known as serverless.
Lambda is a serverless compute platform where you can run code for any type of backend service in response to events.
Compute Service: Run attributes without managing servers.
Event Driven: The code runs when there is a need to run.
🔸How AWS Lambda Works
Upload your code to AWS Lambda.
Set up your code to trigger from another AWS service, an HTTPS endpoint, or an app activity.
Lambda runs your code only when triggered, using only the compute resources needed.
Pay as you go.
🔸Benefits of AWS Lambda
No server to manage: It automatically runs the code without managing servers.
Continuous Scaling: Automatically scales and runs the code in parallel for each individual trigger.
Sub-Second Billing: Charged for every 100ms the code executes and the number of times the code is triggered.
🔸Use Cases of AWS Lambda
Data processing.
App backend development.
Control system.
Serverless websites.
Security updates.
Create a role, but before creating a role, first create a policy.
In service, select Lambda and write the given code in JSON format.
Write the given code
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "ec2:Start*", "ec2:Stop*" ], "Resource": "*" } ] }
Give the policy name
Now, create a role and attach the policy that we have created above
Now, create a function in Lambda.
Use the role that we have created
Successfully, we have created a lambda function. Now, scroll down and write Python code and deploy.
import boto3 region = 'us-west-1' instances = ['i-12345cb6de4f78g9h', 'i-08ce9b2d7eccf6d26'] ec2 = boto3.client('ec2', region_name=region) def lambda_handler(event, context): ec2.stop_instances(InstanceIds=instances) print('stopped your instances: ' + str(instances))
After writing code, go up and click on "Add Trigger."
Select EventBridge in the Trigger configuration. We have created a role, not a rule, so now we will create a rule.
After adding a trigger and a trigger schedule instance will stop (the time you have set in the trigger schedule will stop the EC2 instance, remember it doesn’t stop immediately, it takes 10 sec to 1 min to stop, but remember, the time must be according to UTC.)
Final Output
🚀Conclusion
In this article, we explored how to use AWS Lambda and EventBridge to automate the stopping of EC2 instances at midnight, which is a straightforward yet powerful way to save costs and enhance resource management in AWS. By scheduling a Lambda function with the correct permissions and a cron expression tailored to your time zone, you can ensure that unnecessary instance costs are minimized during non-working hours.
Subscribe to my newsletter
Read articles from Ashwin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ashwin
Ashwin
I'm a DevOps magician, conjuring automation spells and banishing manual headaches. With Jenkins, Docker, and Kubernetes in my toolkit, I turn deployment chaos into a comedy show. Let's sprinkle some DevOps magic and watch the sparks fly!