AWS, Cloud, DevOps & Cloud Solutions, Managed Services

AWS AMI Backup Retention

Data keeps growing and it’s generated from a large number of endpoints like desktops, laptops, servers, virtual machines and many more devices. Automating a solution for backup is cost effective and time saving.

However, trying to leverage traditional, non-cloud native solutions in order to backup AWS resources may be costly and ineffective. Traditional backup software and methods are very centralized by nature, holding disadvantages such as creating single points of failure as well as the high cost of software licenses and required dedicated hardware resources.

This article helps those looking out for a script involving cli commands for AMI  creation  and maintaining a retention of about 30 AMIs as backup .

#!/bin/bash
DateStamp= ‘date +%d%m%y’    
aminame=”anyname_”
reten_secs= ‘date –date ’30 days ago’ +%s’
echo “################################# backup on $DateStamp ######################################”
sync
aws ec2 create-image –instance-id i-efwfeff47 –name “$aminame$DateStamp” –description “$aminame$DateStamp” –no-reboot
if [ $? -eq 0 ] ; then
echo “ami is created successfully ” | mail -s “backup of $aminame server is successful” sri.b@tadigital.com
else
echo “ami is not created properly” | mail -s “alert : backup of $aminame not successful ” sri.b@tadigital.com
fi
echo “##################################################################################################”

echo “################################# deleting AMIs older than 30 days ######################################”
aws ec2 describe-images –filters “Name=name,Values=$aminame*” –query ‘Images[*].{ID:ImageId,Date:CreationDate,SNAPID:BlockDeviceMappings[*].Ebs.SnapshotId}’ –output text > ~/file.txt
cat ~/file.txt | grep -i snapid > ~/snapids
sed -i ‘/SNAPID/d’ ~/file.txt
paste <(cut -d’T’ -f1 ~/file.txt) <(awk ‘{print $NF}’ ~/file.txt) <(awk ‘{print $NF}’ ~/snapids) | sort -n > ~/new.txt

while read -a line
do
ami_secs=’date –date=”${line[0]}” +%s’
if [ $reten_secs -gt $ami_secs ]
then
echo “ami(${line[1]}) is being de-registered and snapshot(${line[2]}) being deleted”
aws ec2 deregister-image –image-id ${line[1]}
sleep 5
aws ec2 delete-snapshot –snapshot-id ${line[2]}
else
echo “No amis have crossed the retention time”
fi
done < ~/new.txt

We can also use a lambda function in conjunction with cloud watch to achieve this , also there are many articles on the internet describing the same .

Note : where ever date is formatted (for eg : ami_secs) it’s the grave accent symbol ( ` ) that is used and not an apostrophe ( ‘ )

About The Author