Skip to content

New serverless pattern - eventbridge-lambda-sns #2789

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions sam-eventbridge-lambda-sns/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# AWS Health Intelligent Notification using Eventbridge, Lambda and SNS

This pattern demonstrates how to build an intelligent AWS Health event monitoring system that automatically captures health events, analyzes them using AI, and sends enhanced notifications.

![Architecture Diagram](diagrams/aws-health-notifications-final-diagram.png)

Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/sam-eventbridge-lambda-sns

Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.

## Requirements

* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed
* [Amazon Bedrock access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) with Claude 3 Haiku model enabled

## Deployment Instructions

1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
```
git clone https://github.com/aws-samples/serverless-patterns
```
2. Change directory to the pattern directory:
```
cd sam-eventbridge-lambda-sns
```
3. From the command line, use AWS SAM to build the serverless application:
```
sam build
```
4. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file:
```
sam deploy --guided
```
5. During the prompts:
* **Stack Name [sam-app]:** Enter a stack name (e.g., `health-notification-setup`)
* **AWS Region [eu-west-1]:** Enter the AWS Region where you want the stack to be deployed
* **Parameter EmailAddress [[email protected]]:** Enter your email address to subscribe to SNS for enhanced health notifications
* **Confirm changes before deploy [y/N]:** Enter `Y` to confirm deployment
* **Allow SAM CLI IAM role creation [Y/n]:** Enter `Y` to allow SAM to create necessary IAM roles
* **Disable rollback [y/N]:** Enter `N` to keep rollback enabled
* **Save arguments to configuration file [Y/n]:** Enter `Y` to save settings for future deployments

Once you have run `sam deploy --guided` mode once and saved parameters to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults.

6. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing.

7. Confirm the SNS email subscription by checking your email and clicking the confirmation link.

## How it works

When AWS Health events occur, EventBridge automatically captures them based on the configured rule pattern. The Lambda function processes these events and leverages Amazon Bedrock's Claude 3 Haiku model to generate intelligent summaries, impact assessments, and actionable recommendations. The enhanced analysis is then formatted and sent via SNS email notifications.

The AI analysis provides three key insights:
- A brief summary of the health event
- Potential impact on your AWS services
- Specific recommended actions to take

This transforms basic health notifications into actionable intelligence, helping teams respond more effectively to AWS service issues.

## Testing

Since AWS Health events can only be published by AWS services and cannot be simulated through EventBridge, we test the pattern by directly invoking the Lambda function with a simulated health event. This approach demonstrates how the function processes health events, calls Bedrock for AI analysis, and sends enhanced notifications.

Once deployed, you can test the Lambda function directly to see the AI-enhanced notifications:

1. **Invoke the deployed Lambda function:**
```bash
aws lambda invoke \
--function-name <Your Lambda function Arn> \
--payload file://test-event.json \
--cli-binary-format raw-in-base64-out \
response.json
```

2. **Check the results:**
- View the response: `cat response.json`
- Check your email for the AI-enhanced notification with:
- Brief summary of the health event
- Potential impact assessment
- Actionable recommendations from Bedrock AI
- Monitor logs: `aws logs tail /aws/lambda/your-function-name`

This demonstrates the complete workflow: EventBridge event → Lambda processing → Bedrock AI analysis → SNS email notification with intelligent insights.

## Cleanup

1. Delete the stack
```bash
sam delete
```
2. During the prompts:
* **Enter stack name you want to delete:** Enter your stack name (e.g., `health-notification-setup`)
* **Are you sure you want to delete the stack [stack-name] in the region [region]? [y/N]:** Enter `y` to confirm stack deletion
* **Are you sure you want to delete the folder [stack-name] in S3 which contains the artifacts? [y/N]:** Enter `y` to delete deployment artifacts
----
Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
69 changes: 69 additions & 0 deletions sam-eventbridge-lambda-sns/example-pattern.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"title": "AWS Health Intelligent Notification using Eventbridge, Lambda and SNS",
"description": "This pattern deploys an EventBridge rule which triggers for health events. The rule invokes Lambda function which sends enhanced health notification to SNS.",
"language": "Python",
"level": "200",
"framework": "SAM",
"introBox": {
"headline": "How it works",
"text": [
"This pattern builds an intelligent AWS Health event monitoring system that automatically captures health events, analyzes them using AI, and sends enhanced notifications.",
"When AWS Health events occur, EventBridge automatically captures them based on the configured rule pattern. The Lambda function processes these events and leverages Amazon Bedrock's Claude 3 Haiku model to generate intelligent summaries, impact assessments, and actionable recommendations. The enhanced analysis is then formatted and sent via SNS email notifications.",
"The AI analysis provides three key insights: a brief summary of the health event, potential impact on your AWS services, and specific recommended actions to take. This transforms basic health notifications into actionable intelligence, helping teams respond more effectively to AWS service issues."
]
},
"gitHub": {
"template": {
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/sam-eventbridge-lambda-sns",
"templateURL": "serverless-patterns/sam-eventbridge-lambda-sns",
"projectFolder": "sam-eventbridge-lambda-sns",
"templateFile": "template.yaml"
}
},
"resources": {
"bullets": [
{
"text": "AWS Health Dashboard and Events",
"link": "https://docs.aws.amazon.com/health/latest/ug/what-is-aws-health.html"
},
{
"text": "Amazon EventBridge Rules for AWS Health",
"link": "https://docs.aws.amazon.com/health/latest/ug/cloudwatch-events-health.html"
},
{
"text": "Amazon Bedrock User Guide",
"link": "https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html"
},
{
"text": "Creating Email Subscription for SNS",
"link": "https://docs.aws.amazon.com/sns/latest/dg/sns-email-notifications.html"
}
]
},
"deploy": {
"text": [
"sam build",
"sam deploy --guided",
"See the GitHub repo for detailed deploying instructions."
]
},
"testing": {
"text": [
"See the GitHub repo for detailed testing instructions."
]
},
"cleanup": {
"text": [
"Delete the stack: <code>same delete</code>.",
"See the GitHub repo for detailed deleting instructions."
]
},
"authors": [
{
"name": "Anirudh Gupta",
"image": "https://drive.google.com/file/d/1aQKx3aY2ID25FpsDI1HS_wSxgIMxOq9J/view?usp=sharing",
"bio": "Technical Account Manager at AWS",
"linkedin": "https://www.linkedin.com/in/anirudh-gupta-13a0b111a/"
}
]
}
125 changes: 125 additions & 0 deletions sam-eventbridge-lambda-sns/handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import json
import boto3
import os
from datetime import datetime

sns = boto3.client('sns')
bedrock = boto3.client('bedrock-runtime')

def process_health_event(event, context):
"""Process AWS Health events and send notifications"""

try:
# Extract health event details
detail = event.get('detail', {})
event_type = detail.get('eventTypeCode', 'Unknown')
service = detail.get('service', 'Unknown')
region = detail.get('eventRegion', 'Unknown')
status = detail.get('statusCode', 'Unknown')

# Handle eventDescription safely
event_descriptions = detail.get('eventDescription', [])
description = 'No description available'

if event_descriptions and len(event_descriptions) > 0:
description = event_descriptions[0].get('latestDescription', 'No description available')

# Get AI analysis from Bedrock
ai_analysis = get_bedrock_analysis(event_type, service, region, status, description)

# Format notification message with AI insights
message = format_notification(event_type, service, region, status, description, ai_analysis)

# Send to SNS (skip if running locally)
sns_topic_arn = os.environ.get('SNS_TOPIC_ARN')
if sns_topic_arn and sns_topic_arn != 'test-topic-arn':
response = sns.publish(
TopicArn=sns_topic_arn,
Subject=f'AWS Health Alert: {event_type}',
Message=message
)
message_id = response['MessageId']
else:
print("Local testing - SNS message would be sent:")
print(f"Subject: AWS Health Alert: {event_type}")
print(f"Message: {message}")
message_id = 'local-test-message-id'

return {
'statusCode': 200,
'body': json.dumps({
'message': 'Health event processed successfully',
'messageId': response['MessageId']
})
}

except Exception as e:
print(f"Error processing health event: {str(e)}")
return {
'statusCode': 500,
'body': json.dumps({'error': str(e)})
}

def get_bedrock_analysis(event_type, service, region, status, description):
"""Get AI analysis from Bedrock"""
try:
prompt = f"""
Analyze this AWS Health event and provide:
1. A brief summary (2-3 sentences)
2. Potential impact on services
3. Recommended actions

Event Details:
- Type: {event_type}
- Service: {service}
- Region: {region}
- Status: {status}
- Description: {description}

Provide a concise, actionable response.
"""

response = bedrock.invoke_model(
modelId='anthropic.claude-3-haiku-20240307-v1:0',
body=json.dumps({
'anthropic_version': 'bedrock-2023-05-31',
'max_tokens': 300,
'messages': [{
'role': 'user',
'content': prompt
}]
})
)

result = json.loads(response['body'].read())
return result['content'][0]['text']

except Exception as e:
print(f"Bedrock analysis failed: {str(e)}")
return "AI analysis unavailable"

def format_notification(event_type, service, region, status, description, ai_analysis):
"""Format the notification message with AI insights"""

timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC')

message = f"""
🚨 AWS Health Event Alert

Event Type: {event_type}
Service: {service}
Region: {region}
Status: {status}
Timestamp: {timestamp}

Description:
{description}

🤖 AI Analysis & Recommendations:
{ai_analysis}

---
This is an automated notification with AI-powered insights.
"""

return message.strip()
1 change: 1 addition & 0 deletions sam-eventbridge-lambda-sns/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
boto3>=1.26.0
63 changes: 63 additions & 0 deletions sam-eventbridge-lambda-sns/template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS Health Event Notifications using SAM

Parameters:
EmailAddress:
Type: String
Default: [email protected]
Description: Email address for health notifications

Globals:
Function:
Timeout: 30
Runtime: python3.11

Resources:
HealthNotificationTopic:
Type: AWS::SNS::Topic
Properties:
TopicName: aws-health-notifications
DisplayName: AWS Health Event Notifications

EmailSubscription:
Type: AWS::SNS::Subscription
Properties:
Protocol: email
TopicArn: !Ref HealthNotificationTopic
Endpoint: !Ref EmailAddress

HealthEventProcessor:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./
Handler: handler.process_health_event
Environment:
Variables:
SNS_TOPIC_ARN: !Ref HealthNotificationTopic
Policies:
- SNSPublishMessagePolicy:
TopicName: !GetAtt HealthNotificationTopic.TopicName
- Statement:
- Effect: Allow
Action:
- bedrock:InvokeModel
Resource: arn:aws:bedrock:*::foundation-model/anthropic.claude-3-haiku-20240307-v1:0
Events:
HealthEvent:
Type: EventBridgeRule
Properties:
Pattern:
source:
- aws.health
detail-type:
- AWS Health Event

Outputs:
SNSTopicArn:
Description: SNS Topic ARN for health notifications
Value: !Ref HealthNotificationTopic

LambdaFunctionArn:
Description: Lambda function ARN
Value: !GetAtt HealthEventProcessor.Arn
Loading