DEV Community

Zareen Khan
Zareen Khan

Posted on

Building Event-Driven Automation with AWS Lambda and EventBridge

How to make your AWS infrastructure self-heal, scale and react intelligently.

Introduction

Imagine a world where your infrastructure fixes itself.
When a server fails — it restarts automatically.
When a deployment finishes — it triggers tests instantly.
When a CloudWatch alarm fires — it sends a Slack alert and creates a Jira ticket.

That’s the power of event-driven automation on AWS.
And at the heart of it all is AWS Lambda — a lightweight, serverless compute engine that reacts to events and runs your custom logic, all without provisioning a single server.

In this post, let’s explore how AWS Lambda + EventBridge can turn your cloud environment into a responsive, automated ecosystem.

What Makes Lambda Special

AWS Lambda is event-driven by design. You upload your code, define triggers and AWS takes care of execution, scaling and availability.

  • No servers to manage
  • Automatic scaling
  • Pay only for the milliseconds your code runs

It’s perfect for lightweight automation tasks such as:

  • Auto-remediation of AWS issues
  • Processing S3 uploads
  • Cleaning up unused resources
  • Sending real-time alerts or notifications

The Core: EventBridge + Lambda

EventBridge (formerly CloudWatch Events) acts as the event router.
It listens for events across AWS (like EC2 instance state changes, ECS task updates, or custom app events) and routes them to targets — most often a Lambda function.

Here’s what the architecture looks like:

Real-World Example: Auto-Restarting an Unhealthy EC2 Instance

Let’s build a simple self-healing automation.

Step 1: Create an EventBridge Rule

This rule listens for EC2 instance state changes that indicate a failed status check.

{
  "source": ["aws.ec2"],
  "detail-type": ["EC2 Instance State-change Notification"],
  "detail": {
    "state": ["stopped", "terminated"]
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Lambda Function

import boto3

ec2 = boto3.client('ec2')

def lambda_handler(event, context):
    instance_id = event['detail']['instance-id']
    print(f"Instance {instance_id} stopped — attempting restart...")

    ec2.start_instances(InstanceIds=[instance_id])
    return {"status": "restarted", "instance": instance_id}
Enter fullscreen mode Exit fullscreen mode

Step 3: Test the Flow

Stop an EC2 instance manually → EventBridge captures the event → Lambda runs automatically and restarts it.

That’s self-healing infrastructure in action

Bonus Tip: Add Notifications

Enhance your Lambda with SNS or Slack notifications:

import json
import boto3
import requests

def lambda_handler(event, context):
    instance_id = event['detail']['instance-id']
    message = f" EC2 Instance {instance_id} was stopped — automatically restarted by Lambda."

    # Example: Send to Slack webhook
    requests.post("https://hooks.slack.com/services/XXXX/XXXX", 
                  data=json.dumps({"text": message}))
Enter fullscreen mode Exit fullscreen mode

Now every time the function runs, your team gets an instant alert.

Deploy as Code (CDK Example)

Use the AWS CDK to define your automation as code — consistent, version-controlled, and deployable.

from aws_cdk import (
    aws_lambda as _lambda,
    aws_events as events,
    aws_events_targets as targets,
    core
)

class AutoHealStack(core.Stack):
    def __init__(self, scope: core.Construct, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)

        fn = _lambda.Function(
            self, "AutoHealFunction",
            runtime=_lambda.Runtime.PYTHON_3_9,
            handler="index.lambda_handler",
            code=_lambda.Code.from_asset("lambda")
        )

        rule = events.Rule(
            self, "EC2StateChangeRule",
            event_pattern=events.EventPattern(
                source=["aws.ec2"],
                detail_type=["EC2 Instance State-change Notification"],
                detail={"state": ["stopped"]}
            )
        )
        rule.add_target(targets.LambdaFunction(fn))

Enter fullscreen mode Exit fullscreen mode

Deploy with a single command:

cdk deploy

AWS Lambda and EventBridge gives you the building blocks for an intelligent, autonomous cloud.
Instead of reacting to problems, your environment can fix itself — automatically, instantly and reliably.

So in this way we can start small and automate one repetitive task and we will soon find countless ways to make our AWS ecosystem smarter.

Top comments (0)