Synapse Solution

  • Home
  • Devops
  • Automate AWS EC2 Backups to S3 Using Lambda – Step-by-Step Guide
May 14, 2025Devops

Automate AWS EC2 Backups to S3 Using Lambda – Step-by-Step Guide

 

Raise your hand if you’ve ever lost sleep worrying about forgetting to back up your EC2 instance.  Let’s fix that with automated AWS backups that work while you sleep!

🚀 Why Automate Backups?

  • 🚨 Disaster Avoidance: Survive “Oops, I deleted the wrong thing” moments
  • ⏰ Reclaim Your Time: No more 2 AM manual backups
  • 📉 Cost Control: S3 + auto-delete = budget-friendly
  • 🔒 Audit-Ready: Proof of backups without spreadsheet chaos

🛠️ What You’ll Need

  • AWS account (Free Tier works!)
  • One EC2 instance you care about
  • 10 minutes and coffee ☕

🔧 Step-by-Step Setup

Step 1: Create Your S3 Backup Vault

  1. Go to S3 Console
  2. Click Create bucket
  3. Name: ec2-backup-vault-[your-initials]
  4. Keep Block Public Access ENABLED
  5. Click Create bucket

Step 2: Create IAM Role

  1. Go to IAM Roles
  2. Create role → Choose Lambda
  3. Attach policies:
    • AmazonEC2FullAccess
    • AmazonS3FullAccess
  4. Name: LambdaBackupMaster

Step 3: Create Lambda Function


import boto3
from datetime import datetime

ec2 = boto3.client('ec2')
s3 = boto3.client('s3')

def lambda_handler(event, context):
    instance_id = 'i-0123456789abcdef0'  # ← Replace!
    volume_id = 'vol-0123456789abcdef0'  # ← Replace!
    
    snapshot = ec2.create_snapshot(
        VolumeId=volume_id,
        Description=f"Autobackup {instance_id} - {datetime.utcnow().strftime('%Y-%m-%d')}"
    )
    
    s3.put_object(
        Bucket='ec2-backup-vault-[your-initials]',  # ← Your bucket name
        Key=f'backup-log/{instance_id}-{datetime.utcnow().isoformat()}.txt',
        Body=f"Backup created at {datetime.utcnow()}:\n{str(snapshot)}"
    )
    
    return {'status': '💪 Backup successful. Go enjoy your day.'}

Step 4: Schedule Daily Backups

  1. In Lambda, click Add trigger
  2. Choose EventBridge (CloudWatch Events)
  3. Create new rule: DailyBackupAlarm
  4. Schedule: rate(1 day)

Step 5: Auto-Delete Old Backups (Optional)

  1. Go to S3 bucket → Management
  2. Create lifecycle rule: 30-DayCleanup
  3. Set expiration: 30 days

🔒 Secure IAM Policy (Bonus)


{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "SnapshotCreateAndS3Log",
      "Effect": "Allow",
      "Action": [
        "ec2:CreateSnapshot",
        "ec2:DescribeVolumes"
      ],
      "Resource": "*"
    },
    {
      "Sid": "WriteToSpecificBucket",
      "Effect": "Allow",
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::ec2-backup-vault-[your-initials]/*"
    }
  ]
}

🎉 You’re Done! Now:

  1. Test your Lambda function
  2. Check S3 for backup logs
  3. Verify EC2 snapshots

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents
Whatsapp Chat