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
- Amazon EC2: The virtual servers we want to manage and stop when not in use.
- AWS Lambda: A lightweight Python function that identifies active instances and sends the stop signal.
- 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.
- Open the Amazon EC2 Console.
- Select your development instance, navigate to the Tags tab, and click Manage tags.
- Add a new tag with Key:
Environmentand Value:Development.
- 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.
- Open the IAM Console and go to Policies -> Create policy.
- 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.
- Name the policy
EC2AutoStopPolicyand save it.
- 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 ). - Navigate to the AWS Lambda Console and click Create function.
- Select Author from scratch, name it
NightlyEC2Stop, and choose Python 3.12.
- Under Execution role, select Use an existing role and pick
EC2AutoStopLambdaRole.
- 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.
- Click Deploy.
Step 4: Schedule the Automation with Amazon EventBridge
Finally, let's trigger this script automatically every night.
- Head over to the Amazon EventBridge Console.
- In the left panel, click Schedules under Scheduler, then click Create schedule.
- Name it
DailyNightlyShutdown.
- Under Schedule pattern, choose Recurring schedule and select Cron-based schedule.
- 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.
- Select AWS Lambda as your target and select your
NightlyEC2Stopfunction.
- 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!
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article