Here’s a couple of proven techniques for backing up your EC2 instances in AWS.

  1. EBS Snapshot – The easiest and most popular method
  2. AMI Creation – Slightly more involved, but includes the OS (C:\ drive) as well.

Each of these can be done via the Management Console (Manual method) as well as automated using terraform and/or bash scripts

EBS Snapshot – Just the EBS volume backup (no C: drive)  Option 1 – Manual Snapshot  (Management Console)

This can be done from the AWS management console (Manual Backup). Find your EBS device from the instance details.

image

 

EBS Snapshot Automated – Automate the EBS Snapshotting – Single EBS Volume

 

#!/bin/bash

ec2-describe-volumes | awk '{ print $2 }' | sort -u >  /tmp/ebs_volumes

for i in $(cat /tmp/ebs_volumes); do
   echo $i;
   ec2-create-snapshot $i;
done

EBS Snapshot Automated – Backing up ALL EC2s in a VPC

 
#!/bin/bash
#Script to Automate AMI backup

echo "----------------------------------\n   `date`   \n----------------------------------"

aws ec2 describe-instances --filters Name=vpc-id,Values=vpc-xxx |   awk '{ print $8 }' | sort -n   | grep  "i-" > /tmp/instanceid.txt

echo "Starting the Daily AMI creation: "

 #To create AMI from instance-id 

for i in $(cat /tmp/instanceid.txt); do
        echo "Creating AMI for Instance id $i ......."


echo "instance-`date +%d%b%y`-$i" > /tmp/aminame.txt

aws ec2 create-image --instance-id $i --name "`cat /tmp/aminame.txt`" --description "This is created by ami-backup.sh" --no-reboot | grep -ir ami | awk '{print $4}' > /tmp/amiID.txt

echo  "AMI Name is: `cat /tmp/aminame.txt`\n"

done

echo done

Method 2 – AMI Creation – Backing up the entire EC2 – including the C: drive

Either bash or terraform code that will create AMI automatically at regular intervals.

Terraform

module "lambda_ami_backup" {
  source = "git::https://github.com/cloudposse/terraform-aws-ec2-ami-backup.git?ref=tags/0.3.2"

  name           = "${var.name}"
  stage          = "${var.stage}"
  namespace      = "${var.namespace}"
  region         = "${var.region}"
  ami_owner      = "${var.ami_owner}"
  instance_id    = "${var.instance_id}"
  retention_days = "14"
}

Summary

Backing up EC2 instances is a popular use case on AWS. There’s a couple of proven techniques – EBS snapshots being the most popular one.

Anuj holds professional certifications in Google Cloud, AWS as well as certifications in Docker and App Performance Tools such as New Relic. He specializes in Cloud Security, Data Encryption and Container Technologies.

Initial Consultation

Anuj Varma – who has written posts on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.