-->

Monday, February 1, 2016

Script to Delete AMI and associated Snapshots

While working on the Console, if you are going to deregister the AMI in the Amazon console , it doesn't remove the snapshots associated with that AMI. It will only deregister the AMI after which you won't be able to figure out which all snapshots were left behind.



You can probably note the associated snapshot and delete them manually after deleting the AMI, or even search ami-id in the console under the snapshots and delete them manually. Which can be a problem in case you are considering deleting number of the AMI's and snapshots, since you will still be billed for the same unless you delete them.

You can use the following bash script to delete the AMI's and associated snapshots with them. The script takes upto 5 AMI-ids as arguments. You can increase it if you want to delete more AMI's and snapshots.


 #!/bin/bash  
 #Script to delete ami with attached snapshots.  
 echo -e "$1" > /tmp/imageid.txt  
 echo -e "$2" >> /tmp/imageid.txt  
 echo -e "$3" >> /tmp/imageid.txt  
 echo -e "$4" >> /tmp/imageid.txt  
 echo -e "$5" >> /tmp/imageid.txt  
 for i in `cat /tmp/imageid.txt`;do aws ec2 describe-images --image-ids $i | grep snap | awk '{print $2}' | cut -d "\"" -f2 > /tmp/snap.txt;  
 echo -e "Following are the snapshots associated with it :\n`cat /tmp/snap.txt`\n ";  
 echo -e "Starting the Deregister of AMI... \n";  
 #Deregistering the AMI  
 aws ec2 deregister-image --image-id $i  
 deregister=$?  
 if [ $deregister -eq 0 ];then  
   echo "Sucessfully Deregistered the AMI..."  
 else  
   echo "Deregister failed, manual intervention required"  
 fi  
 echo -e "\nDeleting the associated snapshots.... \n"  
 #Deleting snapshots attached to AMI  
 for j in `cat /tmp/snap.txt`;do aws ec2 delete-snapshot --snapshot-id $j ; done  
 snap=$?  
 if [ $snap -eq 0 ];then  
   echo "Sucessfully Deleted the Snapshots..."  
 else  
   echo "Snapshot Deletion failed, manual intervention required"  
 fi  
 done  

0 comments:

Post a Comment