Skip to content

Instantly share code, notes, and snippets.

@daniilyar
Last active October 25, 2023 11:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniilyar/45d3fc1867bf435d8c21e9e4864ff472 to your computer and use it in GitHub Desktop.
Save daniilyar/45d3fc1867bf435d8c21e9e4864ff472 to your computer and use it in GitHub Desktop.
AWS: check if there is no orphaned EBS snapshots (orphaned == not attached to any 'available' AMI)
#!/bin/bash
set -e
AWS_ACCOUNT_ID=<ENTER_YOUR_ACCOUNT_ID_HERE>
REGION=us-west-2
ORPHANED_SNAPSHOTS_COUNT_LIMIT=10
WORK_DIR=/tmp
aws ec2 --region $REGION describe-snapshots --owner-ids $AWS_ACCOUNT_ID --query Snapshots[*].SnapshotId --output text | tr '\t' '\n' | sort > $WORK_DIR/all_snapshots
aws ec2 --region $REGION describe-images --filters Name=state,Values=available --owners $AWS_ACCOUNT_ID --query "Images[*].BlockDeviceMappings[*].Ebs.SnapshotId" --output text | tr '\t' '\n' | sort > $WORK_DIR/snapshots_attached_to_ami
ORPHANED_SNAPSHOT_IDS=`comm -23 <(sort $WORK_DIR/all_snapshots) <(sort $WORK_DIR/snapshots_attached_to_ami)`
if [ -z "$ORPHANED_SNAPSHOT_IDS" ]; then
echo "OK - no orphaned (not attached to any AMI) snapshots found"
exit 0
fi
ORPHANED_SNAPSHOT_IDS=`echo "$ORPHANED_SNAPSHOT_IDS" | grep "snap"`
ORPHANED_SNAPSHOTS_COUNT=`echo "$ORPHANED_SNAPSHOT_IDS" | wc -l`
if (( ORPHANED_SNAPSHOTS_COUNT > ORPHANED_SNAPSHOTS_COUNT_LIMIT )); then
echo "CRITICAL - $ORPHANED_SNAPSHOTS_COUNT orphaned (not attached to any AMI) snapshots found: [ $ORPHANED_SNAPSHOT_IDS ]"
echo "To delete them, use commands below:"
IFS=$'\n'
for snapshot_id in $ORPHANED_SNAPSHOT_IDS; do echo "aws ec2 --region us-west-2 delete-snapshot --snapshot-id $snapshot_id"; done
exit 1
else
echo "OK - $ORPHANED_SNAPSHOTS_COUNT orphaned (not attached to any AMI) snapshots found"
if (( ORPHANED_SNAPSHOTS_COUNT > 0 )); then
echo "[ $ORPHANED_SNAPSHOT_IDS ]"
fi
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment