Skip to content

Instantly share code, notes, and snippets.

@karl-johan-grahn
Created June 21, 2022 07:07
Show Gist options
  • Save karl-johan-grahn/6e7d5d2ea3f069fcc1df58260da16a91 to your computer and use it in GitHub Desktop.
Save karl-johan-grahn/6e7d5d2ea3f069fcc1df58260da16a91 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -euo pipefail
usage () {
echo "script syntax: -a AWS account nickname
-r AWS region
-h This help text";
}
options=':a:r:h'
while getopts $options option
do
case $option in
a ) AWS_PROFILE_NAME=$OPTARG;;
r ) AMI_REGIONS=$OPTARG;;
h ) usage; exit;;
\? ) echo "ERROR: Unknown option: -$OPTARG" >&2; exit 1;;
: ) echo "ERROR: Missing argument value for -$OPTARG" >&2; exit 1;;
esac
done
shift $(($OPTIND - 1))
if [[ -z "$AWS_PROFILE_NAME" ]]; then
echo "ERROR: Missing argument - please provide the AWS account's profile name."
exit 1
fi
AMI_REGIONS=${AMI_REGIONS:-"us-east-1 eu-west-1 ap-southeast-2"}
for region in $AMI_REGIONS; do
images=$(aws ec2 describe-images --profile $AWS_PROFILE_NAME --region $region --owners <ID> --output text --query 'Images[*].ImageId')
for i in $images; do
instances=$(aws ec2 describe-instances --profile $AWS_PROFILE_NAME --region $region --filters "Name=image-id,Values=$i" | jq '.Reservations | has(0)')
if [ "$instances" == "true" ]; then
echo "$i has an instance and will not be deregistered"
else
echo "$i does not have an instance and will be deregistered"
# Run describe-images command (OSX/Linux/UNIX) using the ID of the unused AMI (see the Audit section for getting the unused AMIs metadata) as identifier to return the ID of the EBS snapshot associated with the selected image
#snapshot=$(aws ec2 describe-images --profile $AWS_PROFILE_NAME --region $region --image-ids $i --output text --query 'Images[*].BlockDeviceMappings[*].Ebs.SnapshotId')
# Once you identified the AMI snapshot ID run deregister-image command (OSX/Linux/UNIX) using the image ID as identifier to deregister the selected AMI (the command does not produce an output)
#aws ec2 deregister-image --profile $AWS_PROFILE_NAME --region $region --image-id $i
# Finally, run delete-snapshot command (OSX/Linux/UNIX) using the ID returned at step no. 2 as identifier, to complete the removal/cleanup process by deleting the snapshot associated with the selected image (if successful, the command does not return an output)
#aws ec2 delete-snapshot --profile $AWS_PROFILE_NAME --region $region --snapshot-id $snapshot
fi
done
#snapshot=$(aws ec2 describe-snapshots --profile stage --region us-east-1 --filters "Name=owner-id,Values=<ID>" --output text --query '[Snapshots[*].Description]')
#regex=".*for (ami-.*) from.*"
# ${BASH_REMATCH[1]}
# Set images again against no owner-id
# Then check if snapshot is part of that list
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment