Created
March 27, 2020 21:36
-
-
Save aboritskiy/f9ba106de2ff43bdfdde5da10430e241 to your computer and use it in GitHub Desktop.
Interactively removes AWS snapshots that were created by CreateImage but AMI was removed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -eu | |
AWS_ACCOUNT_ID=657433956652 | |
echo "Snapshots exist for following images: " | |
aws ec2 describe-snapshots --filters Name=description,Values="Created by CreateImage*" --owner-id=$AWS_ACCOUNT_ID --output=text | grep "^SNAPSHOTS" | sed 's/.*\(ami-[0-9a-z]\+\).*/\1/' | sort | uniq | sort > /tmp/snapshot-cleanup-existing-snapshots | |
echo "Following images exist: " | |
aws ec2 describe-images --owners=$AWS_ACCOUNT_ID --output=text | grep IMAGES | sed 's/.*\(ami-[0-9a-z]\+\).*/\1/' | sort | uniq | sort > /tmp/snapshot-cleanup-existing-images | |
echo "Snapshots for those images can be deleted: " | |
ORPHAED_AMIS=$(diff /tmp/snapshot-cleanup-existing-snapshots /tmp/snapshot-cleanup-existing-images | grep "^< ami" | sed 's/.*\(ami-[0-9a-z]\+\).*/\1/' | sort | uniq) | |
for OAMI in $ORPHAED_AMIS | |
do | |
echo | |
echo "Removing $OAMI:" | |
aws ec2 describe-snapshots --filters Name=description,Values="Created by CreateImage*${OAMI}*" --owner-id=$AWS_ACCOUNT_ID --output=text | grep "^SNAPSHOTS" | |
echo | |
read -p " proceed? " -n 1 -r | |
if [[ $REPLY =~ ^[Yy]$ ]] | |
then | |
echo " deleting..." | |
SNAPSHOTS_TO_DELETE=$(aws ec2 describe-snapshots --filters Name=description,Values="Created by CreateImage*${OAMI}*" --owner-id=$AWS_ACCOUNT_ID --output=text | grep "^SNAPSHOTS" | sed 's/.*\(snap-[0-9a-z]\+\).*/\1/') | |
for SNAP in $SNAPSHOTS_TO_DELETE | |
do | |
echo $SNAP | |
aws ec2 delete-snapshot --snapshot-id $SNAP | |
done | |
echo " deleted" | |
echo | |
echo | |
fi | |
done | |
rm /tmp/snapshot-cleanup-existing-snapshots || true | |
rm /tmp/snapshot-cleanup-existing-images || true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment