Skip to content

Instantly share code, notes, and snippets.

@okochang
Created March 16, 2012 05:33
Show Gist options
  • Save okochang/2048681 to your computer and use it in GitHub Desktop.
Save okochang/2048681 to your computer and use it in GitHub Desktop.
ami backup script for ec2 instance
#!/bin/sh
## EC2 confiration
export JAVA_HOME="Set your java home path"
export EC2_HOME="Set your ec2 home path"
export EC2_PRIVATE_KEY="Set your aws private-key"
export EC2_CERT="Set your your X509-cert"
export EC2_URL="Set using ec2 url"
export EC2_REGION="Set using ec2 region"
## Basic Set up
TODAY=`date +%Y%m%d`
INSTANCE_ID="Set your intence-id to be backed up"
INSTANCE_NAME="Set your instance-name to be backed up"
LOG="Set log file path"
MAX="Set number of generation"
## Start backup
echo 'start backup' > ${LOG}
echo ${TODAY} >> ${LOG}
## Create Amazon Machine Image
ec2-create-image ${INSTANCE_ID} --name ${INSTANCE_NAME}-${TODAY} --no-reboot
## Sleep until the end of the processing
sleep 2m
## Check Amazon Machine Image
AMIS=`ec2-describe-images \
| grep ${INSTANCE_NAME} | sort -k3 -r | awk '{print $2}'`
## Check Snapshot
SNAPSHOTS=`ec2-describe-images \
| grep -A 1 ${INSTANCE_NAME} | awk '{if(NR%2)ORS=" ";else ORS="\n";print}' | sort -k3 -r | awk '{print $15}'`
## Deregister AMI
COUNT=1
for AMI in ${AMIS}; do
if [ ${COUNT} -le ${MAX} ]; then
echo "${AMI} keeping AMI"
else
ec2-deregister ${AMI} \
-K ${EC2_PRIVATE_KEY} \
-C ${EC2_CERT}
echo "${AMI} deregisterd AMI"
fi
COUNT=`expr ${COUNT} + 1`
done
## Delete Snapshot
COUNT=1
for SNAPSHOT in ${SNAPSHOTS}; do
if [ ${COUNT} -le ${MAX} ]; then
echo "${SNAPSHOT} keeping Snapshot"
else
ec2-delete-snapshot ${SNAPSHOT} \
-K ${EC2_PRIVATE_KEY} \
-C ${EC2_CERT}
echo "${SNAPSHOT} deleted Snapshot"
fi
COUNT=`expr ${COUNT} + 1`
done
## Backup log
ec2-describe-images \
| grep -A 1 ${INSTANCE_NAME} | awk '{if(NR%2)ORS=" ";else ORS="\n";print}' | sort -k3 -r >> ${LOG}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment