Reduce AWS Bills by 60%: Automate EC2 Stop/Start with Python & Lambda



In 2026, cloud bills have become a top expense for most tech companies. One of the biggest "money-wasters" is leaving Development and Staging servers running over the weekend or at night when no one is using them.

If you have a t3.large instance running 24/7, you're paying for 168 hours a week. By shutting it down outside of 9-to-5 working hours, you can save over 65% on your monthly bill.

The Solution: "The DevSecOps Auto-Stop"

We will use a small Python script running on AWS Lambda that looks for a specific tag (like Schedule: OfficeHours) and shuts down any instance that shouldn't be running.

Step 1: Tag Your Instances

First, go to your AWS Console and add a tag to the instances you want to automate:

  • Key: AutoStop

  • Value: True

Step 2: The Python Script (Boto3)

Create a new AWS Lambda function and paste this code. It uses the boto3 library to talk to your EC2 instances.

import boto3

ec2 = boto3.client('ec2', region_name='us-east-1') # Change to your region

def lambda_handler(event, context):
# Search for all running instances with the 'AutoStop' tag
filters = [
{'Name': 'tag:AutoStop', 'Values': ['True']},
{'Name': 'instance-state-name', 'Values': ['running']}
]
instances = ec2.describe_instances(Filters=filters)
instance_ids = []

for reservation in instances['Reservations']:
for instance in reservation['Instances']:
instance_ids.append(instance['InstanceId'])

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 tag.")


Step 3: Set the Schedule (EventBridge)

You don't want to run this manually.

  1. Go to Amazon EventBridge.

  2. Create a "Schedule."

  3. Use a Cron expression to trigger the Lambda at 7:00 PM every evening:

    • cron(0 19 ? * MON-FRI *)

No comments:

Post a Comment

Reduce AWS Bills by 60%: Automate EC2 Stop/Start with Python & Lambda

In 2026, cloud bills have become a top expense for most tech companies. One of the biggest "money-wasters" is leaving Development ...