AWS Builder Center

Preventing Cloud Bill Shock: Automating Ec2 Shutdowns Using AWS Lambda and EventBridge

Forgot to turn off your test servers? Learn how to schedule automatic nightly shutdowns for AWS EC2 instances using a serverless Lambda function and Amazon EventBridge.

Preventing Cloud Bill Shock: Automating EC2 Shutdowns Using AWS Lambda and EventBridge

One of the most common experiences for students learning cloud computing is accidentally leaving an Amazon EC2 instance running over the weekend, leading to an unexpected bill. While the AWS Free Tier is generous, cloud cost optimization (FinOps) is a critical skill that production environments demand. 
Instead of trying to remember to turn off your virtual servers manually every evening, you can automate the process. In this tutorial, we will build a serverless scheduler that automatically shuts down designated development EC2 instances every night at a specific time. 



🛠️ The Architecture

  1. Amazon EC2: The virtual servers we want to manage and stop when not in use. 
  1. AWS Lambda: A lightweight Python function that identifies active instances and sends the stop signal. 
  1. Amazon EventBridge Schedules: A serverless cron job scheduler that triggers our Lambda function automatically at a set time daily. 



🚀 Step-by-Step Implementation

Step 1: Tag Your EC2 Instances

To avoid stopping production or critical databases, our automation script will only target servers that have a specific tag. 
  1. Open the Amazon EC2 Console. 
  1. Select your development instance, navigate to the Tags tab, and click Manage tags. 
  1. Add a new tag with Key:  Environment  and Value:  Development . 
  1. Click Save. 

Step 2: Create an IAM Policy and Role for Lambda

The Lambda function needs specific authorization to look for and stop running EC2 instances. 
  1. Open the IAM Console and go to Policies -> Create policy. 
  1. Switch to the JSON tab and paste the following policy: 
json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances",
"ec2:StopInstances"
],
"Resource": "*"
}
]
}

Use code with caution.
  1. Name the policy  EC2AutoStopPolicy  and save it. 
  1. Go to Roles -> Create role, choose Lambda, attach this new policy, and name the role  EC2AutoStopLambdaRole . 

Step 3: Write the Auto-Stop Lambda Function

Next, let's write a quick automation script using Python and the AWS SDK ( boto3 ). 
  1. Navigate to the AWS Lambda Console and click Create function. 
  1. Select Author from scratch, name it  NightlyEC2Stop , and choose Python 3.12. 
  1. Under Execution role, select Use an existing role and pick  EC2AutoStopLambdaRole . 
  1. Replace the sample code with this custom script: 
python
import boto3

ec2 = boto3.client('ec2')

def lambda_handler(event, context):
# Filter for instances that are running AND have the Development tag
filters = [
{'Name': 'instance-state-name', 'Values': ['running']},
{'Name': 'tag:Environment', 'Values': ['Development']}
]
# Locate matching instances
response = ec2.describe_instances(Filters=filters)
instance_ids = []
for reservation in response['Reservations']:
for instance in reservation['Instances']:
instance_ids.append(instance['InstanceId'])
# Stop the instances if any are found
if instance_ids:
ec2.stop_instances(InstanceIds=instance_ids)
print(f"Successfully stopped instances: {instance_ids}")
else:
print("No running development instances found.")
return {
'statusCode': 200,
'body': f"Processed {len(instance_ids)} instances."
}

Use code with caution.
  1. Click Deploy. 

Step 4: Schedule the Automation with Amazon EventBridge

Finally, let's trigger this script automatically every night. 
  1. Head over to the Amazon EventBridge Console. 
  1. In the left panel, click Schedules under Scheduler, then click Create schedule. 
  1. Name it  DailyNightlyShutdown . 
  1. Under Schedule pattern, choose Recurring schedule and select Cron-based schedule. 
  1. Set the cron expression to run at your desired time (e.g.,  0 22 * * ? *  to run every night at 10:00 PM UTC). Click Next. 
  1. Select AWS Lambda as your target and select your  NightlyEC2Stop  function. 
  1. Review and click Create schedule. 



🧪 Testing Your Cost-Saving Machine

You do not have to wait until night to test this setup. Go to your AWS Lambda Console, click on the Test tab, create a dummy test event, and hit Test. Check your EC2 console; your running instance with the  Environment: Development  tag will gracefully transition into a stopping state. 



🎯 Conclusion

With this serverless architecture, you protect your wallet from unexpected cloud bills while demonstrating a strong grasp of AWS automation tools. Employers highly value developers who build solutions with cost-efficiency in mind!
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article