Created
December 26, 2022 12:59
-
-
Save ademidoff/dab66d9dc0b5bbac7108959e5f8eae7b to your computer and use it in GitHub Desktop.
Purge AMI images and their snapshots
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
# get a list of AMI Images in a region | |
aws ec2 describe-images --owners self --filters "Name=tag:name,Values=PMM2 Server*" --region us-east-1 --output json | jq '.Images' > ~/IMAGES.json | |
# save just AMI IDs and their snapshot IDs | |
jq -r '.[] | .ImageId + " " + .BlockDeviceMappings[1].Ebs.SnapshotId' IMAGES.json > IMAGES_AND_SNAPSHOTS.txt | |
# first deregister the image | |
for AMI_ID in $(cat IMAGES_AND_SNAPSHOTS.txt); do | |
if [[ "$AMI_ID" =~ snap-* ]]; then | |
continue | |
fi | |
echo "Deregistering AMI ID: $AMI_ID ..." | |
aws ec2 deregister-image --image-id $AMI_ID && echo "AMI ID: $AMI_ID deregistered." || echo "Error: could not deregister AMI ID: $AMI_ID" | |
sleep 2 | |
done | |
# wait until the snapshots become available for deletion | |
sleep 120 | |
# then delete its snapshot | |
for SNAPSHOT_ID in $(cat IMAGES_AND_SNAPSHOTS.txt); do | |
if [[ "$SNAPSHOT_ID" =~ ami-* ]]; then | |
continue | |
fi | |
echo "Deleting snapshot ID: $SNAPSHOT_ID ..." | |
aws ec2 delete-snapshot --snapshot-id $SNAPSHOT_ID && echo "Snapshot ID: $SNAPSHOT_ID deleted." || echo "Error: could not delete snapshot ID: $SNAPSHOT_ID" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment