Automating EC2 Shutdown with Lambda, EventBridge & SNS –



This content originally appeared on DEV Community and was authored by Glory Ugochukwu

In cloud computing, efficiency is everything. Imagine you’re managing cloud infrastructure with multiple EC2 instances running. We often deploy EC2 instances for testing, learning, or short-term tasks. Some are used for batch jobs and dev environments. Often, these instances are left running overnight, leading to unnecessary billing. What if you could automate shutting them down—say, every night at 10 PM—and even receive an email confirmation when it happens?

This article walks through a real-world automation project that uses AWS Lambda, Amazon EventBridge, SNS, and Python to stop an EC2 instance on a schedule—and send an email notification when it’s done.

It’s simple, cost-effective, and powerful. And yes, it was part of a real hands-on training session where I executed the entire workflow. Let’s dive in.

Why Automate EC2 Shutdown?
In real cloud environments—especially dev or training setups—it’s common to:

  • Forgot to stop EC2 instances after use.(I have had to pay bills due to forgotten instances running)
  • Leave dev/test environments running overnight or over weekends.
  • Lose track of idle instances when managing multiple resources.

Here’s what this automation solves: Real-World Applications & Why It Matters

  • Cost control: Automatically stop dev/test environments after business hours. saving you money.
  • Resource Management: Free up unused compute resources.
  • Operational discipline: Prevent unnecessary resource usage and reduce risk.
  • Operational Efficiency: Reduce manual intervention and human error.
  • Security: Shut down public-facing instances during off-hours for added security.
  • Accountability: Get notified (via email) every time your automation runs.
  • Scalability: Apply this pattern across environments and projects.
  • Integration: Use it as part of a broader CI/CD or infrastructure automation strategy.

Scenario and Benefits
Student or Trainee environments: Avoid surprise AWS bills during self-paced learning.

Dev/Test teams: Automatically shut down EC2 environments after office hours.

Cloud Budgets for Startups: Enforce spending discipline without constant human effort.

CI/CD Pipelines: Tear down staging environments after deployment testing.

Freelancers/Consultants: Manage client projects efficiently and remotely.

Services We’ll Use

  1. EC2 (Elastic Compute Cloud) – the target of the automation (the instance you want to stop).

  2. IAM (Identity and Access Management)– because Lambda needs permissions to stop an EC2 instance, I attached a role with ec2:StopInstances permission.

  3. AWS Lambda– the brain of the operation. Serverless compute. where I wrote the Python function to stop the instance.

  4. EventBridge (formerly CloudWatch Events)– this acts like a scheduler. I used this to trigger the Lambda at a specific time or interval.

  5. SNS (Simple Notification Service) – this one was optional, but I wanted to get a confirmation that “Hey, your instance has been stopped!” without going back into the console. So I used SNS to send an email notification.

What is AWS Lambda? AWS Lambda is a serverless computing service where you upload your code, and AWS runs it automatically in response to events. An event-driven infrastructure.

Step-by-Step Implementation
Here are the exact steps I followed,

  1. Launch an EC2 Instance: that we want to automatically stop. Note the Instance ID—you’ll use it in your Lambda function.

Instance created

  1. Create an SNS Topic & Email Subscription
  2. Create the topic:
  3. Navigate to Amazon SNS >** Topics** > Create topic.
  4. Choose Standard.
  5. Name: StopEC2Topic.

Topic created

Create an email subscription:

  • Go to the topic **> **Create subscription.
  • Protocol: Email
  • Endpoint: Your email address.
  • Confirm the subscription from your inbox.

subscription created
Email Confirmation
Subscription confirmed

Step 3: Create the Lambda Function
Go to:

  • AWS Lambda > Create Function
  • Name: StopEC2Function
  • Runtime: Python 3.9 or any…
  • Execution role: Create a new role with basic Lambda permissions or attach the role you created.

created lambda function
Replace code with:

`import boto3

def lambda_handler(event, context):
    ec2 = boto3.client('ec2')
    sns = boto3.client('sns')

    instance_id = 'i-0123456789abcdef0'  # Replace with your Instance ID
    topic_arn = 'arn:aws:sns:region:account-id:StopInstanceTopic'  # Replace with your SNS Topic ARN

    # Stop EC2 instance
    ec2.stop_instances(InstanceIds=[instance_id])

    # Send notification
    message = f"EC2 Instance {instance_id} has been stopped successfully."
    sns.publish(TopicArn=topic_arn, Subject="EC2 Shutdown Notice", Message=message)

    return {
        'statusCode': 200,
        'body': message
    }
`

deployed the code

  1. Add Permissions to Lambda Role: ** Update IAM Role with Required Permission**
  • Go to IAM > Roles, find the role created with Lambda, and attach the following permissions: AmazonEC2FullAccess AmazonSNSFullAccess

Alternatively, create a role with these permissions and attach it when creating your Lambda function.

Step 5: Create an EventBridge Rule
To schedule the shutdown:

  • Go to Amazon EventBridge > Rules.
  • Click Create rule.
  • Name: StopEC2Schedule
  • Define schedule:Choose cron expression (e.g., cron(0 22 * * ? *) for 10 PM daily)
  • Target: Select Lambda Function, then choose the Lambda you created

Rule created

Step 6: Add EventBridge as a Trigger to Lambda

  • Go back to your Lambda function:
  • Click Add trigger
  • Choose EventBridge (CloudWatch Events)
  • Select the rule you just created

Added to the function

Instance automatically stopped within the scheduled time

And That’s It!
You’ve built a fully automated EC2 shutdown system with:

  • Scheduled execution via EventBridge
  • Logic handled in a Lambda function
  • Email alert via SNS And the best part? You don’t need to keep a server running or manually intervene to execute this logic. It’s 100% serverless and scalable.

Bonus Tips
-You can extend this to start instances in the morning. Say, start instances at 8 AM automatically.

  • Add multiple instance IDs if you need to manage more than one.
  • Log actions to CloudWatch for auditing.
  • Use Tags to identify instances for stopping (e.g., AutoStop = true).
  • Extend this for RDS or S3 lifecycle automation

Conclusion
Cloud Server automation is a powerful superpower. It isn’t just for massive enterprise projects. Even small use cases like this one can save money, reduce errors, and simplify your cloud usage. This is also a great portfolio project for anyone preparing for AWS certifications or roles like Cloud Support Engineer or Solutions Architect.
Try it, customize it, and make it yours.

By: Glory Ugochukwu – AWS Solution Architect Trainee


This content originally appeared on DEV Community and was authored by Glory Ugochukwu