Backup your EC2 instances on AWS
Here’s a couple of proven techniques for backing up your EC2 instances in AWS.
- EBS Snapshot – The easiest and most popular method
- 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.
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.
Leave a Reply