Wednesday, 12 October 2016

AWS Script TO Delete Old AMI and There Asociated Snapshots.



AWS Script TO Delete Old AMI and There Asociated Snapshots.


# To collect all amis from specific account in to single file called allAMI.txt
#!/bin/bash
aws ec2 describe-images --region ap-southeast-1 --owners 121212123456 | grep ami | awk '{print $3 " " $9}' | cut -d 'T' -f 1-3 --output-delimiter=' ' | awk '{print $1 " " $3}' > allAMI.txt

for i in `cat allAMI.txt | awk '{print $1}'`
do
if [ "$i" == "$(date +%Y-%m-%d --date '3 days ago')" ];
then
echo "3 days older AMI ID is stored in amiid.txt file"
grep $i allAMI.txt | awk '{print $2}' > amiid.txt

else
echo "No older AMI image found"
fi
done

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

## This script used to delete ami and snapshots:


cat ami-delete.sh

#Find snapshots associated with AMI.
aws ec2 describe-images --image-ids `cat /root/amiid.txt` | grep snap | awk ' { print $4 }' > /root/snap.txt

echo -e "Following are the snapshots associated with it : `cat /root/snap.txt`:\n "

echo -e "Starting the Deregister of AMI... \n"

#Deregistering the AMI
for i in `cat /root/amiid.txt` ; do aws ec2 deregister-image --image-id $i ; done

echo -e "\nDeleting the associated snapshots.... \n"

#Deleting snapshots attached to AMI
for i in `cat /root/snap.txt`;do aws ec2 delete-snapshot --snapshot-id $i ; done
sleep 3
> allAMI.txt
> snap.txt



## Setup cron jobs for Auto Delete AMI - Snapshots

30 3 * * * /bin/sh /root/main.sh >> /root/main-log.txt
33 3 * * * /bin/sh /root/ami-delete.sh >> /root/ami-delete.txt

5 comments:

Automated Snapshots EC2 said...

You shared very useful script via this blog post. It helps to delete old AMI. Thanks for sharing

Unknown said...

Very informative, thanks for sharing your information AWS Online Course Hyderabad

Unknown said...

Thanks for comments

Unknown said...

Thanks

Anonymous said...

Awesome! I was looking for this one. Many thanks :)