Automate EC2 Backups Using AWS Lambda and EventBridge.

Automate EC2 Backups Using AWS Lambda and EventBridge.

Introduction

Imagine it’s Monday morning, and one of your production EC2 instances suddenly becomes unavailable after an application deployment. The quickest way to recover is by restoring a recent EBS snapshot. But what if no recent backup exists?

Many organizations still rely on manual snapshot creation, which is time-consuming, inconsistent, and prone to human error. Missing even one scheduled backup can result in data loss and longer recovery times.

AWS provides a powerful serverless solution to automate this entire process using AWS LambdaAmazon EventBridge, and the Amazon EC2 API. By combining these services, you can create scheduled EBS snapshots without managing any servers or installing additional software.

In this tutorial, you’ll build a production-ready backup automation solution that:

  1. Automatically creates EBS snapshots
  2. Runs on a schedule
  3. Requires zero server management
  4. Sends logs to CloudWatch
  5. Can easily scale to multiple EC2 instances

By the end of this guide, you’ll have a fully automated backup solution that can be adapted for development, testing, and production workloads.

Why Automate EC2 Backups?

Manual backups may work for one or two instances, but they quickly become difficult to manage as infrastructure grows.

Consider an environment with:

  1. 20 EC2 instances
  2. Multiple EBS volumes
  3. Daily backup requirements
  4. Compliance policies
  5. Disaster recovery objectives

Performing snapshots manually every day is inefficient and increases the likelihood of missed backups.

Automation provides several advantages:

Benefits

Improved Reliability

Snapshots are created consistently according to schedule.

Reduced Human Error

No administrator needs to remember backup windows.

Cost Effective

Since Lambda executes only when needed, you pay only for execution time.

Scalable

The same solution works for one instance or hundreds.

Serverless

No EC2 instance is required to run backup scripts.

Solution Architecture

Our solution consists of four AWS services.

                +———————-+               | Amazon EventBridge   |                 | Daily Schedule       |                +———-+———–+                            |                            |                            v                  +——————-+                  | AWS Lambda        |                  | Python Function   |                  +———+———+                            |                            |                            v                +———————–+                | Amazon EC2 API        |                | Create Snapshot       |                +———-+————+                           |                           |                           v                  +——————+                  | Amazon EBS       |                  | Snapshot Created |                  +——————+                           |                           v                   CloudWatch Logs

Workflow

  1. EventBridge triggers Lambda every day.
  2. Lambda discovers the EC2 instance.
  3. Lambda identifies attached EBS volumes.
  4. Lambda creates snapshots.
  5. Logs are written to CloudWatch.
  6. Snapshot becomes available for recovery.

AWS Services Used

Amazon EC2

Hosts the virtual machines whose EBS volumes will be backed up.

Amazon EBS

Provides persistent block storage.

Snapshots are incremental backups stored in Amazon S3 internally.

AWS Lambda

Executes Python code without provisioning servers.

Our Lambda function will:

  1. Find EC2 volumes
  2. Create snapshots
  3. Add descriptions
  4. Write logs

Amazon EventBridge

Acts as a scheduler.

Instead of running cron jobs on EC2, EventBridge invokes Lambda automatically.

Amazon CloudWatch

Captures logs and execution details.

Useful for:

  1. Monitoring
  2. Debugging
  3. Auditing

Prerequisites

Before starting, ensure you have:

  1. AWS Account
  2. One running EC2 instance
  3. Attached EBS volume
  4. IAM permissions to create:
    • Lambda
    • EventBridge Rule
    • IAM Roles
    • EBS Snapshots

Step 1 – Create an IAM Role

Lambda needs permission to communicate with EC2.

Navigate to:

IAM
→ Roles → Create Role

Choose

Trusted Entity AWS Service Use Case Lambda Attach the following policies: AmazonEC2FullAccess CloudWatchLogsFullAccess

Note: For production environments, follow the principle of least privilege by creating a custom IAM policy that grants only the specific permissions required, such as ec2:DescribeInstancesec2:DescribeVolumesec2:CreateSnapshot, and CloudWatch Logs actions.

Role Name:

EC2SnapshotLambdaRole

Create the role.

Step 2 – Create the Lambda Function

Navigate to

AWS Lambda Create Function Author From Scratch

Configuration:

Function Name: EC2SnapshotAutomation Runtime: Python 3.12 Architecture: x86_64 Execution Role: Use Existing Role EC2SnapshotLambdaRole

Click Create Function.

Step 3 – Python Code

Replace the default Lambda code with the following:

import boto3 from datetime import datetime ec2 = boto3.client(‘ec2’) INSTANCE_ID = ‘i-0123456789abcdef0’ def lambda_handler(event, context):     reservations = ec2.describe_instances(         InstanceIds=[INSTANCE_ID]     )[‘Reservations’]     for reservation in reservations:         for instance in reservation[‘Instances’]:             for mapping in instance[‘BlockDeviceMappings’]:                 volume_id = mapping[‘Ebs’][‘VolumeId’]                 snapshot = ec2.create_snapshot(                     VolumeId=volume_id,                     Description=f”Automated Snapshot {datetime.utcnow()}”                 )                 print(                     f”Snapshot created: ”                     f”{snapshot[‘SnapshotId’]}”                 )     return {         “statusCode”: 200,         “body”: “Snapshots Created Successfully”     }

Understanding the Code

Let’s break down what this function does.

Create an EC2 Client

ec2 = boto3.client(‘ec2’)

This initializes the Boto3 client used to interact with the EC2 service.

Specify the EC2 Instance

INSTANCE_ID = ‘i-0123456789abcdef0’

Replace the placeholder value with the ID of your EC2 instance.

Describe the Instance

describe_instances()

This API call retrieves information about the instance and its attached storage volumes.

Find Attached Volumes

The function iterates through:

BlockDeviceMappings

to identify every EBS volume attached to the instance.

Create Snapshot

create_snapshot()

AWS immediately begins creating a snapshot in the background.

Log Output

Each snapshot ID is written to CloudWatch Logs for auditing and troubleshooting.

shamitha
shamitha
Leave Comment
Share This Blog
Recent Posts
Get The Latest Updates

Subscribe To Our Newsletter

No spam, notifications only about our New Course updates.

Enroll Now
Enroll Now
Enquire Now