Create an AMI of EBS-backed-Instance for backup

This is an excerpt from script running on an chef build debian ec2 instance.

OS – Debain Squeeze

Assuming EC2-API tools are installed and configured.

Also the export the environment variable (to avoid using -C and -K flags in command)

export EC2_PRIVATE_KEY=/root/ec2-certs/pk-47OH3YSOZRKGXYH4P2MXKW6YDEKOHGGV.pem
export EC2_CERT=/root/ec2-certs/cert-47OH3YSOZRKGXYH4P2MXKW6YDEKOHGGV.pem

###### To obtain instance ID #########

#inst_id=`cat /opt/smart/log.txt | grep Instance | awk {‘print $3’}`

The above command is used in a chef based instance. The log.txt is output redirection of the knife create command

inst_id=i-s123456

Command to create an AMI —
#ec2-create-image -n “Test unni” –description “To be deleted” –no-reboot i-f123456


printf “`ec2-create-image -n “Instance-name-$Cur” –description “Instance-info-$Cur” –no-reboot $inst_id` `date +%Y-%m-%d`\n” >> /opt/scripts/ami.txt


Note: The printf command is used to log ami-ids in a chronological order by putting dates beside it.

############# Snapshots Log ####################

##Assuming 2 ebs is attached which appears as /dev/sda and /dev/sdi in the instance.

amiid=`cat /opt/scripts/ami.txt | grep $Cur |awk {‘print $2’}`

printf “`ec2-describe-images $amiid | grep /dev/sda | awk {‘print $3’}` `date +%Y-%m-%d` `echo /dev/sda`\n” >> /opt/scripts/ami_snapshots.txt

printf “`ec2-describe-images $amiid | grep /dev/sdi | awk {‘print $3’}` `date +%Y-%m-%d` `echo /dev/sdi`\n” >> /opt/scripts/ami_snapshots.txt

#################### Deregister AMI ###############
# Retention Policy 5 days

amiold=`cat /opt/scripts/ami.txt | grep $C |awk {‘print $2’}`
ec2-deregister $amiold

############# Delete Sanpshots ####################
snap1=`cat /opt/scripts/ami_snapshots.txt | grep $C | grep /dev/sda | awk {‘print $1’}`
snap2=`cat /opt/scripts/ami_snapshots.txt | grep $C | grep /dev/sdi | awk {‘print $1’}`

ec2-delete-snapshot $snap1
ec2-delete-snapshot $snap2

Other Useful related commands are:
*ec2-describe-images
*ec2-describe-snapshots

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s