Last active
April 21, 2020 13:30
-
-
Save dmc5179/65f82dce03cc98e0cefdb04f4c76b7fc to your computer and use it in GitHub Desktop.
Script to find AWS EC2 Snapshots created for AMIs that no longer exist
This file contains 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 | |
# Locate dead AWS EC2 Snapshots | |
# This program is free software: you can redistribute it and/or modify | |
# it under the terms of the GNU General Public License as published by | |
# the Free Software Foundation, either version 3 of the License, or | |
# (at your option) any later version. | |
# | |
# This program is distributed in the hope that it will be useful, | |
# but WITHOUT ANY WARRANTY; without even the implied warranty of | |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
# GNU General Public License for more details. | |
# | |
# You should have received a copy of the GNU General Public License | |
# along with this program. If not, see <https://www.gnu.org/licenses/>. | |
function show_help() { | |
echo "$0: -o <owner id> -r <aws-region> -p <aws-cli-profile> -v" | |
} | |
OPTIND=1 # Reset in case getopts has been used previously in the shell. | |
# Initialize our own variables: | |
OWNER="" | |
VERBOSE=0 | |
REGION="us-east-1" | |
PROFILE="default" | |
while getopts "h?vo:r:p:" opt; do | |
case "$opt" in | |
h|\?) | |
show_help | |
exit 0 | |
;; | |
v) VERBOSE=1 | |
;; | |
o) OWNER="--owner-ids ${OPTARG}" | |
;; | |
r) REGION=$OPTARG | |
;; | |
p) PROFILE=$OPTARG | |
;; | |
esac | |
done | |
shift $((OPTIND-1)) | |
[ "${1:-}" = "--" ] && shift | |
SNAPSHOTS="/tmp/snapshots.txt" | |
aws --profile ${PROFILE} --region ${REGION} ec2 describe-snapshots ${OWNER} --output text --query 'Snapshots[*].SnapshotId' > ${SNAPSHOTS} | |
if [[ ${VERBOSE} == 1 ]] | |
then | |
SNAPCOUNT=$(grep -o 'snap' ${SNAPSHOTS} | wc -l) | |
echo "Scanning ${SNAPCOUNT} snapshots" | |
fi | |
for snap in $(cat ${SNAPSHOTS}) | |
do | |
if [[ ${VERBOSE} == 1 ]] | |
then | |
echo "Checking: $snap" | |
fi | |
DESC=$(aws --profile ${PROFILE} --region ${REGION} ec2 describe-snapshots --snapshot-ids ${snap} --output text --query 'Snapshots[*].Description') | |
if [[ "${DESC}" =~ .*"Created by CreateImage".* ]] | |
then | |
AMI=$(echo "$DESC" | grep -oP "(ami-[0-9a-z]*)") | |
aws --profile ${PROFILE} --region ${REGION} ec2 describe-images --image-ids ${AMI} 2> /dev/null > /dev/null || echo "Dead: ${snap}" | |
fi | |
done | |
rm -f ${SNAPSHOTS} | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment