Skip to content

New serverless pattern - Eventbridge-EBS-Snapshot #2791

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 2 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
76 changes: 76 additions & 0 deletions sam-eventbridge-ebs-snapshot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Automated EBS Snapshot Creation on EC2 Shutdown using EventBridge

This pattern demonstrates how to automatically create EBS snapshots when an EC2 instance shuts down using EventBridge with direct EBS snapshot target integration. It helps protect data on stateful applications or self-managed databases by capturing the volume state during instance shutdown events, reducing data loss risk and increasing recovery flexibility.

## Architecture

EC2 Instance State Change → EventBridge Rule → EBS CreateSnapshot (Direct Target)

![EventBridge EBS Snapshot Architecture](./generated-diagrams/eventbridge-ebs-snapshot-diagram.png)

## Requirements

* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) installed
* EBS Volume ID that you want to snapshot
* EC2 Instance ID to monitor for shutdown events

## Deployment

1. Clone and navigate to the pattern directory: sam-eventbridge-ebs-snapshot
2. Build the application:
```bash
sam build
```
3. Deploy with guided prompts:
```bash
sam deploy --guided
```
4. Follow the deployment prompts:
- Stack Name: Enter `ebs-snapshot-automation` (default is `sam-app`)
- AWS Region: Enter `us-east-1` (or your preferred region)
- Parameter VolumeId: Enter your EBS Volume ID (e.g., `vol-0abcd123456ef7890`)
- Parameter InstanceId: Enter your EC2 Instance ID (e.g., `i-0abcd123456ef7890`)
- Confirm changes before deploy: Enter `Y`
- Allow SAM CLI IAM role creation: Enter `Y`
- Disable rollback: Enter `N`
- Save arguments to configuration file: Enter `Y`

## How it Works

- EventBridge rule monitors EC2 instance state changes
- Rule triggers when the specified instance enters "shutting-down" or "stopping" state
- Rule directly targets EBS snapshot creation service using built-in target
- No Lambda functions or custom code required
- Snapshots are created automatically for the specified volume ID
- Pure infrastructure-as-code approach

## Scope and Limitations

- This pattern targets a single EBS volume specified via the VolumeId parameter
- It does not automatically detect or snapshot all volumes attached to an instance
- Works with EBS volumes of any size (snapshot creation is asynchronous and incremental)
- Only triggers on graceful EC2 state changes (stopping, shutting-down, terminated)
- Will not capture snapshots during abrupt failures where no state change event is emitted

## Use Cases

- Protecting stateful applications or self-managed databases running on EC2
- Preserving data during EC2 instance stop/terminate events (patching, maintenance)
- Safeguarding against accidental shutdowns during testing

## Testing

Stop or terminate the monitored EC2 instance, then check your EC2 console snapshots section. A snapshot will be created automatically when the instance shuts down.

## Cleanup

```bash
sam delete
```

**Note:** This will not delete existing snapshots. Clean up snapshots manually if needed.

---
Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
65 changes: 65 additions & 0 deletions sam-eventbridge-ebs-snapshot/example-pattern.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"title": "Automated EBS Snapshot Creation on EC2 Shutdown using EventBridge",
"description": "This pattern deploys an EventBridge rule that automatically creates EBS snapshots when an EC2 instance shuts down using direct EBS target integration.",
"language": "CloudFormation",
"level": "100",
"framework": "SAM",
"introBox": {
"headline": "How it works",
"text": [
"This pattern creates an automated EBS snapshot system using EventBridge event-driven rules with direct EBS target integration.",
"The EventBridge rule monitors EC2 instance state changes and triggers when an instance enters shutting-down or stopping state.",
"The solution requires Volume ID and Instance ID parameters and uses pure infrastructure-as-code approach without Lambda functions."
]
},
"gitHub": {
"template": {
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/sam-eventbridge-ebs-snapshot",
"templateURL": "serverless-patterns/sam-eventbridge-ebs-snapshot",
"projectFolder": "sam-eventbridge-ebs-snapshot",
"templateFile": "template.yaml"
}
},
"resources": {
"bullets": [
{
"text": "Amazon EventBridge Event Rules",
"link": "https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-rules.html"
},
{
"text": "Amazon EBS Snapshots",
"link": "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html"
},
{
"text": "EventBridge Built-in Targets",
"link": "https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-targets.html"
}
]
},
"deploy": {
"text": [
"sam build",
"sam deploy --guided"
]
},
"testing": {
"text": [
"Stop or terminate the monitored EC2 instance after deployment.",
"Check EC2 console snapshots section - snapshot will be created when instance shuts down."
]
},
"cleanup": {
"text": [
"sam delete",
"Note: Existing snapshots must be deleted manually if needed."
]
},
"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/"
}
]
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
71 changes: 71 additions & 0 deletions sam-eventbridge-ebs-snapshot/template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
AWSTemplateFormatVersion: '2010-09-09'
Description: Automated EBS Snapshot Creation on EC2 Shutdown using EventBridge

Parameters:
VolumeId:
Type: String
Description: EBS Volume ID to snapshot (e.g., vol-0abcd123456ef7890)
AllowedPattern: ^vol-[0-9a-f]{8,17}$
ConstraintDescription: Must be a valid EBS Volume ID

InstanceId:
Type: String
Description: EC2 Instance ID to monitor (e.g., i-0abcd123456ef7890)
AllowedPattern: ^i-[0-9a-f]{8,17}$
ConstraintDescription: Must be a valid EC2 Instance ID

Resources:
SnapshotRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: events.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: CreateSnapshotPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: ec2:CreateSnapshot
Resource: '*'

EC2ShutdownSnapshotRule:
Type: AWS::Events::Rule
Properties:
Description: Create EBS snapshot when EC2 instance shuts down
EventPattern:
source:
- aws.ec2
detail-type:
- EC2 Instance State-change Notification
detail:
state:
- shutting-down
- stopping
instance-id:
- !Ref InstanceId
State: ENABLED
Targets:
- Arn: !Sub 'arn:aws:events:${AWS::Region}:${AWS::AccountId}:target/create-snapshot'
Id: EBSSnapshotTarget
RoleArn: !GetAtt SnapshotRole.Arn
Input: !Sub '"${VolumeId}"'


Outputs:
EventRuleArn:
Description: EventBridge Rule ARN
Value: !GetAtt EC2ShutdownSnapshotRule.Arn

VolumeId:
Description: EBS Volume being snapshotted
Value: !Ref VolumeId

InstanceId:
Description: EC2 Instance being monitored
Value: !Ref InstanceId