Day 47: AWS Lambda (Automatically Stopping EC2 Instances With AWS Lambda and EventBridge)
#90daysofdevops
🚀 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 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 in which its running is fully managed, provisioned and scaled by AWS.
Scale with usage.
No server to provision or manage.
Never pay for idle.
Less 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 server-less compute platform where you can run a code for any type of backend service in response to events.
Compute Service: Run attributes without managing servers.
Event Driven: The code run when there is a need to run.
🔸How AWS Lambda Works
Upload your code to AWS Lambda.
Set up you code to trigger from other AWS service, HTTPS endpoint or in app activity.
Lambda runs your code only when triggered, using only the compute resource 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 execute 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 role, but before creating role first create policy.
In service select Lambda and write given code in JSON format.
Write 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 policy name
Now create role and attach policy that we have created above
Now Create function in lambda.
Use that role that we have created
Successfully we have created 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 Trigger configuration. We have created role not rule so now we will create rule.
After adding trigger and trigger schedule instance will stop (the time you have set in trigger schedule will stop the ec2 instance, remember it don’t stop immediately it take 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.
Thanks for reading to the end; I hope you gained some knowledge.❤️🙌
Lambda to stop/start EC2 instances using EventBridge (AWS Official Documentation)