All Linux HowTo's

Create backups (AMIs) of all running EC2s using a Bash Script

This article shows how you can backup all of your running EC2 instances using a Bash script. In this example we’re ensuring the machines are not rebooted at any time in the process. Also, these images are AMI file that we’d eventually delete because they will simply grow in numbers and increase costs.

The example below shows that i’m using “profiles”. “profiles” allow you to specify which AWS account you want to use. Therefore you can have multiple AWS accounts and switch between them. A “profile” in an option that can be used with the “aws” command that allow you to manage multiple AWS accounts. For example, suppose i have two AWS accounts and i want to manage one of them and then the other using the AWS command, i’d simply configure the AWS command like this:

aws configure --profile account1
aws configure --profile account2

And any time i run the AWS command i add the “–profile accountX” to specify which account i’m using. Anyway, that aside, the following accounts for multiple accounts but you can simply ignore that.

#!/bin/bash

# AGIX (andrew.galdes@agix.com.au).
# Create an image (AMI) or each running EC2 instance in the single region.
#       Instances are NOT rebooted.

### OPTIONS ###

#the AWS account i want to use. 
AWSPROFILE="agix" 

### END OPTIONS ###

# Create a list of running EC2's.
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId]' --filters Name=instance-state-name,Values=running --output text --profile ${AWSPROFILE} > /tmp/aws.${AWSPROFILE}.running

# Cycle through the list and start the iamgeing process.
DATE=`date +%Y-%m-%d`
for INSTANCE in `cat /tmp/aws.${AWSPROFILE}.running`
do
        echo "Starting to create the image for instance ${INSTANCE}"
        aws ec2 create-image --instance-id ${INSTANCE} --name "Backup of ${INSTANCE} on ${DATE} by AGIX" --no-reboot --profile ${AWSPROFILE}
done

echo "The process will continue for some time..."

Similar Posts: