I recently worked with a client where there were a number of Amazon EC2 AMIs where not all of the disk volumes were set to delete on termination. This caused quite a few snapshots to become orphaned when the associated AMI was deleted. This was discovered when there were hundreds of snapshots and no active snapshot plan.
To fix this issue, I wrote a script that will loop through all snapshots that have been created as part of a AMI and deleting them if that AMI no longer exists.
Note that this process should be used with a process to set all volumes to delete on termination to prevent future orphans.
This script requires the EC2 command line tools.
Note that you should be 100% comfortable with this script before running it as it will delete snapshots. On the other hand, they are only snapshots, it will not delete EC2 instances.
#!/bin/bash
images=$(ec2-describe-images | awk '/IMAGE/ {print $2}')
invalid_count=0
valid_count=0
IFS='
'
for snapshot in $(ec2-describe-snapshots)
do
snapshotid=$(echo ${snapshot} | sed -n 's/.*\(snap-[a-z0-9]\{4,8\}\).*/\1/p')
amiid=$(echo ${snapshot} | sed -n 's/.*\(ami-[a-z0-9]\{4,8\}\).*/\1/p')
if [ -z ${amiid} ]
then
# not related to AMI
continue;
fi
valid=$(echo ${images} | egrep -c ${amiid})
if [ "${valid}" -gt 0 ]
then
valid_count=$((valid_count+1))
else
echo "Deleting orphaned snapshot ${snapshotid} which belongs to non-existent AMI ${amiid}"
invalid_count=$((invalid_count+1))
ec2-delete-snapshot ${snapshotid}
fi
done
unset IFS
echo "Valid snapshots: ${valid_count}"
echo "Invalid snapshots: ${invalid_count}"
exit 0;
Let me know if you find any issues.
– josh
Leave a Reply