Shell Script to Automatically Create an AMI Backup of an EC2 Instance (AWS)




Requirements: 

- Access to a Linux machine where shell script will be created
- Access keys to an Amazon Web Services (AWS) Account where the EC2 Instance is hosted


Script name: ami-bash.sh

Input: Name of the instance

How to run: ami-backup.sh <instance_name>

What it does: 

1.  Asks for INSTANCE_NAME

2.  Sets the LOG directory and LOGFILE to record execution

3.  Runs the AWS CLI describe-instances to extract the INSTANCE_ID

4.  Sets the name of the AMI IMAGE_NAME  

5.  Runs the AWS CLI create-image to create the AMI

6.  Runs a loop to check if the image has been created and available

Finished result: An AMI backup of the instance


Script:
=================================================================================
# name:  ami-backup.sh
# usage: ami-backup.sh <instance_name>
#        ami-backup.sh my-db-instance

INSTANCE_NAME=$1

LOGDIR=/tmp/log
LOGFILE=${LOGDIR}/ami-backup-$INSTANCE_NAME-$(date +"%Y-%m-%d-%H-%M-%S").log

INSTANCE_ID=`aws ec2 -describe-instances --filters \
    "Name=tag:Name,Values=$INSTANCE_NAME" \
    | grep "InstanceId" \
    | grep -Po ': "\K[^"]*'`
IMAGE_NAME=ami-backup-$INSTANCE_NAME-$(date +"%Y-%m-%d-%H-%M")

echo "$(date +"%Y-%m-%d-%H:%M:%S") ami-backup.sh started." >> $LOGFILE
echo "$IMAGE_NAME AMI will be created." >> $LOGFILE

IMAGE_ID=`aws ec2 create-image --instance-id $INSTANCE_ID \
     --name "$IMAGE_NAME" \
     --description "$INSTANCE_NAME AMI - $(date +"%Y-%m-%d-%H-%M")" \
     | grep -Po ': "\K[^"]*'`

while [ true ]
do
   echo "AMI creation in progress..." >> $LOGFILE
   IMAGE_CREATION_STATUS=`aws ec2 describe-images --filters \
      "Name=name,Values=$IMAGE_NAME" | grep "State" | grep -Po ': "\K[^"]*'`
      echo "AMI $IMAGE_NAME created." >> $LOGFILE
      break
   fi
   sleep 300
done

echo "$(date +"%Y-%m-%d-%H:%M:%S") ami-backup.sh completed." >> $LOGFILE

=================================================================================



=================================================================================

Amazon Photo by Igor Shalyminov on Unsplash