Skip to content

Instantly share code, notes, and snippets.

@VMuliadi
Created November 18, 2019 22:08
Show Gist options
  • Select an option

  • Save VMuliadi/0beae2d6c24fcccb4c73c6904974a1fe to your computer and use it in GitHub Desktop.

Select an option

Save VMuliadi/0beae2d6c24fcccb4c73c6904974a1fe to your computer and use it in GitHub Desktop.
Delete AWS EBS Snapshot that older than a year. Deleted EBS are checked before deletion by checking the AWS EBS volume is deleted or not exist to prevent any disastrous face palm in your AWS account
#!/bin/bash
ACCOUNT_ID=$1
if [[ -z ${ACCOUNT_ID} || -s ${ACCOUNT_ID} ]]; then
echo "How to use this script?"
echo "./delete_ebs_snapshot.sh <AWS_ACCOUNT_ID>"
exit 1
fi
if [[ ! $(command -v jq) ]]; then echo "Please install jq"; fi
if [[ ! $(command -v aws) ]]; then echo "Please install awscli"; fi
SNAPSHOTS="aws-describe-snapshot.json"
if [[ ! -f ${SNAPSHOTS} ]]; then
echo "Generating JSON from your AWS EBS Snapshot from your account"
aws ec2 describe-snapshots --owner-ids ${ACCOUNT_ID} --output json > ${SNAPSHOTS}
fi
A_YEAR_AGO=$(expr $(date +%s) - 31536000)
for counter in $(seq 0 $(cat ${SNAPSHOTS} | jq '.Snapshots | length')); do
VOLUME_ID=$(cat ${SNAPSHOTS} | jq .Snapshots[${counter}].VolumeId | tr -d '"')
SNAPSHOT_ID=$(cat ${SNAPSHOTS} | jq .Snapshots[${counter}].SnapshotId | tr -d '"')
SNAPSHOT_DESC=$(cat ${SNAPSHOTS} | jq .Snapshots[${counter}].Description | tr -d '"')
SNAPSHOT_CREATION_TIME=$(cat ${SNAPSHOTS} | jq 'select(has("OwnerAlias") | not)' | jq .Snapshots[${counter}].StartTime | tr -d '"')
if [[ ! -s ${SNAPSHOT_DESC} && ! -z ${SNAPSHOT_DESC} && ${SNAPSHOT_DESC} != "null" ]]; then
if [[ ! $(aws ec2 describe-volumes --volume-ids ${VOLUME_ID} 2&>1 /dev/null) ]]; then
if [[ ${SNAPSHOT_CREATION_TIME} -lt ${A_YEAR_AGO} ]]; then
echo "Deleting ${SNAPSHOT_ID} since created in $(echo ${line} | awk '{print $5}')"
aws ec2 delete-snapshot --snapshot-id ${SNAPSHOT_ID} 2&>1 /dev/null # quiet mode
fi
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment