How to clean orphaned EBS SnapShots in Amazon Web Services

Managing AWS resources is the key and i believe is the single most important thing you need to do as AWS consumer.  Amazon will give access to unlimited resources so do get carried away. From time to time you will have EBS SnapShots stacking up so for this i use this easy script to identify and remove EBS SnapShots that are not attached to any AMI.

#!/bin/bash


set -e

AWS_ACCOUNT_ID=self
REGION=ap-southeast-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 $REGION 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
This script will identify and generate the delete command. Note: - review the script before you go ahead on the delete path.