Step-by-Step Instructions for Setting Up EC2 Backup Using Lambda

Here’s a detailed guide to set up an automated backup of your EC2 instance using AWS Lambda:

Step 1: Launch Your EC2 Instance

  1. Launch an EC2 Instance:
    • Go to the EC2 dashboard in the AWS Management Console.
    • Click “Launch Instance” and follow the wizard to create an instance with the required specifications.
  2. Install AWS CLI on the EC2 Instance (if not already installed):
sudo apt-get update
sudo apt-get install awscli -y

Step 2: Create an S3 Bucket

  1. Create an S3 Bucket:
    • Go to the S3 dashboard in the AWS Management Console.
    • Click “Create Bucket” and follow the prompts to create a bucket that will store your backups.
aws s3 mb s3://my-ec2-backup-bucket

Step 3: Create an IAM Role for Lambda

  1. Create IAM Role:
    • Go to the IAM dashboard in the AWS Management Console.
    • Click “Roles” and then “Create role”.
    • Select “Lambda” as the trusted entity.
    • Attach the following policies:
      • AmazonS3FullAccess
      • AmazonEC2ReadOnlyAccess
      • AWSLambdaBasicExecutionRole
    • Name the role (e.g., LambdaEC2BackupRole).

Step 4: Create the Lambda Function

  1. Create a Lambda Function:
    • Go to the Lambda dashboard in the AWS Management Console.
    • Click “Create function”.
    • Choose “Author from scratch”, name your function (e.g., EC2BackupFunction), select Python as the runtime, and use the IAM role created in the previous step.
  2. Write the Lambda Code:
  3. In the Lambda console, replace the default code with the following Python code:
import boto3
import json
from datetime import datetime

def lambda_handler(event, context):
    ec2_client = boto3.client('ec2')
    s3_client = boto3.client('s3')
    
    bucket_name = 'my-ec2-backup-bucket'  # replace with your bucket name
    instance_ids = event.get('instance_ids', [])

    backup_results = []
    
    for instance_id in instance_ids:
        try:
            # Get volumes attached to the instance
            volumes = ec2_client.describe_volumes(
                Filters=[
                    {
                        'Name': 'attachment.instance-id',
                        'Values': [instance_id]
                    }
                ]
            )
            
            for volume in volumes['Volumes']:
                volume_id = volume['VolumeId']
                # Create snapshot
                snapshot = ec2_client.create_snapshot(
                    Description=f'Backup snapshot for {instance_id}',
                    VolumeId=volume_id
                )
                snapshot_id = snapshot['SnapshotId']

                # Tag snapshot
                ec2_client.create_tags(
                    Resources=[snapshot_id],
                    Tags=[
                        {'Key': 'Name', 'Value': f'Backup-{instance_id}-{datetime.now().strftime("%Y%m%d%H%M%S")}'}
                    ]
                )

                # Record the snapshot info
                backup_results.append({
                    'InstanceId': instance_id,
                    'VolumeId': volume_id,
                    'SnapshotId': snapshot_id
                })

                # Upload snapshot details to S3 (optional)
                snapshot_file = f"/tmp/backup-{instance_id}-{volume_id}-{datetime.now().strftime('%Y-%m-%dT%H-%M-%S')}.snapshot"
                with open(snapshot_file, 'w') as f:
                    f.write(str(snapshot))

                s3_client.upload_file(snapshot_file, bucket_name, snapshot_file)
                
        except Exception as e:
            backup_results.append({
                'InstanceId': instance_id,
                'Error': str(e)
            })

    return {
        'statusCode': 200,
        'body': json.dumps(backup_results)
    }

  1. Set Environment Variables:
    • In the Lambda console, under the “Configuration” tab, go to “Environment variables” and set the following variables:
    • BUCKET_NAME (your S3 bucket name)

Step 2: Create a Test Event

Next, create a test event in the Lambda console to pass the list of Lambda functions. Here’s an example of how the test event should look:

{
  "instance_ids": [
    "i-0abcd1234efgh5678", // pass to instance id of ec2 instance which you want to backup 
    "i-0wxyz1234efgh5678",
    "i-0ijkl1234efgh5678",
  ]
}

Step 5: Set Up CloudWatch Events

  1. Create a CloudWatch Event Rule:
    • Go to the CloudWatch dashboard in the AWS Management Console.
    • Click “Rules” under “Events” and then “Create rule”.
    • Choose “Event Source” as “Schedule” and set the rule to trigger at desired intervals (e.g., daily).
    • AWScloudrule
  2. Add Lambda Function as Target:
    • Under “Targets”, select “Lambda function” and choose the Lambda function created earlier.
  3. Configure the Rule:
    • Name the rule (e.g., DailyEC2Backup) and click “Create rule”.

Step 6: Testing

  1. Trigger Lambda Manually:
    • Go to the Lambda function and click “Test”.
    • Create a test event (you can use a blank JSON object {}) and execute it to ensure everything is working.
  2. Verify Backup in S3:
    • Go to your S3 bucket and check if the backup file has been created and uploaded.

Similar Posts

Leave a Reply

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