Automating EC2 Shutdowns Using Lambda and CloudWatch Events
Managing AWS EC2 instances efficiently is crucial to controlling cloud costs and ensuring optimal resource usage. Automating the shutdown of unused or idle EC2 instances is a powerful approach to achieve this. In this guide, we’ll learn how to use AWS Lambda and Amazon CloudWatch Events (now EventBridge) to schedule and automate EC2 shutdowns.
Why Automate EC2 Shutdowns?
Manually managing EC2 instance uptime can lead to human error and increased costs. Automation brings:
Cost Optimization: Shut down unused resources outside business hours.
Improved Security: Reduce attack surface when instances are not in use.
Operational Efficiency: Remove dependency on manual intervention.
Prerequisites
To implement this solution, ensure the following:
An AWS account with the necessary permissions
At least one running EC2 instance
AWS IAM Role with appropriate Lambda and EC2 permissions
Basic understanding of AWS Lambda and CloudWatch Events
Step-by-Step Implementation
1. Create an IAM Role for Lambda
This role must allow the Lambda function to stop EC2 instances.
Policy Example:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:StopInstances",
"ec2:DescribeInstances"
],
"Resource": "*"
}
]
}
2. Write Your Lambda Function
Go to the AWS Lambda Console and create a new function. Select Python or Node.js runtime. Here's a simple Python script to stop specific EC2 instances:
import boto3
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name='us-east-1')
instances = ['i-0123456789abcdef0'] # Replace with your instance IDs
ec2.stop_instances(InstanceIds=instances)
print(f'Stopped instances: {instances}')
Ensure your Lambda function is associated with the IAM role you created earlier.
3. Create a CloudWatch Rule
Navigate to Amazon EventBridge (CloudWatch Events) and:
Click on Create Rule
Select Schedule as the event type
Define a cron expression (e.g., cron(0 20 * * ? *) for 8 PM UTC daily)
Set the target as the Lambda function you created
Save and enable the rule.
Testing the Setup
Manually invoke the Lambda function to verify that it stops the EC2 instance correctly. You can also monitor logs in Amazon CloudWatch Logs for debugging.
Security Best Practices
Limit the IAM role to only required actions.
Use instance tags to filter which EC2 instances should stop.
Enable logging and monitoring with CloudWatch.
Bonus: Stopping Tagged EC2 Instances Automatically
For flexibility, stop only instances with a specific tag:
def lambda_handler(event, context):
ec2 = boto3.resource('ec2', region_name='us-east-1')
instances = ec2.instances.filter(
Filters=[{'Name': 'tag:AutoShutdown', 'Values': ['true']}]
)
for instance in instances:
instance.stop()
Comments
Post a Comment