AWS Builder Center
Title: How to Automatically Stop Idle Dev Instances on AWS Using EventBridge and Lambda

Title: How to Automatically Stop Idle Dev Instances on AWS Using EventBridge and Lambda

Tags: AWS Lambda, Amazon EC2, FinOps, DevOps, Automation

Nick
Managing AWS infrastructure costs is often less about optimizing production workloads and more about keeping non-production environments under control. A common budget leak comes from development and testing instances left running overnight or across entire weekends.
Here is a lightweight, serverless approach to automate the shutdown of tagged development resources without relying on third-party SaaS tools.


Step 1: Tag the Resources
Standardize your resource tagging across all non-production instances. Add a simple key-value pair to every development EC2 instance:
  • Key:  AutoStop 
  • Value:  true 


Step 2: Create the IAM Role
Create a basic IAM role for AWS Lambda with permissions to describe and stop EC2 instances:
  •  ec2:DescribeInstances 
  •  ec2:StopInstances 
  •  logs:CreateLogGroup ,  logs:CreateLogStream ,  logs:PutLogEvents 


Step 3: Deploy the Python Lambda Function
Set up a standard Python 3.12 Lambda function that queries instances with the targeted tag and issues a stop command:
import boto3
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
filters = [
{'Name': 'tag:AutoStop', 'Values': ['true']},
{'Name': 'instance-state-name', 'Values': ['running']}
]
instances = ec2.describe_instances(Filters=filters)
instance_ids = [
i['InstanceId']
for r in instances['Reservations']
for i in r['Instances']
]
if instance_ids:
ec2.stop_instances(InstanceIds=instance_ids)
print(f"Successfully stopped instances: {instance_ids}")
else:
print("No running instances found with AutoStop=true.")



Step 4: Configure the EventBridge Schedule
Create an Amazon EventBridge recurring schedule rule to trigger the function automatically:
  • Schedule Expression:  cron(0 19 ? * MON-FRI *)  (Runs every weekday at 7:00 PM UTC)
  • Target: Your newly created Lambda function.


Setting up this pattern takes under 15 minutes and immediately prevents dev environments from racking up unnecessary runtime hours during off-work periods.
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