Skip to content

Instantly share code, notes, and snippets.

@elasticdog
Last active March 7, 2023 12:19
Show Gist options
  • Select an option

  • Save elasticdog/11152144 to your computer and use it in GitHub Desktop.

Select an option

Save elasticdog/11152144 to your computer and use it in GitHub Desktop.
Deregister an Amazon Machine Image (AMI) and delete its corresponding root device snapshot
#!/usr/bin/env bash
#
# delete-ami
#
# A script to deregister an Amazon Machine Image (AMI) and
# delete its corresponding root device snapshot.
#
##### Functions
# print a message to stderr
warn() {
local fmt="$1"
shift
printf "delete-ami: $fmt\n" "$@" >&2
}
# print a message to stderr and exit with either
# the given status or that of the most recent command
die() {
local st="$?"
if [[ "$1" != *[^0-9]* ]]; then
st="$1"
shift
fi
warn "$@"
exit "$st"
}
##### Main
# check command line arguments
if [[ -z $1 ]]; then
printf 'Usage: delete-ami AMI-ID\n'
printf 'Deregister the given AMI and delete its root device snapshot\n'
exit 1
else
AMI_ID=$1
fi
# check for dependencies
for cmd in {aws,jq}; do
if ! command -v $cmd > /dev/null; then
die 1 'required command "%s" was not found' "$cmd"
fi
done
AMI_DESCRIPTION=$(aws ec2 describe-images --image-ids "$AMI_ID" 2> /dev/null)
if [[ -z $AMI_DESCRIPTION ]]; then
warn 'unable to find an AMI with the ID "%s"' "$AMI_ID"
die 1 'run the following command to debug:\n aws ec2 describe-images --image-ids "%s"' "$AMI_ID"
fi
ROOT_DEVICE_NAME=$(printf "$AMI_DESCRIPTION" | jq --raw-output '.[][].RootDeviceName')
SNAPSHOT_ID=$(printf "$AMI_DESCRIPTION" | jq --raw-output ".[][].BlockDeviceMappings | .[] | select(.DeviceName == \"$ROOT_DEVICE_NAME\") | .Ebs.SnapshotId")
if [[ -z $SNAPSHOT_ID ]]; then
warn 'unable to find a Snapshot ID for the "%s" root device on %s' "$ROOT_DEVICE_NAME" "$AMI_ID"
die 1 'run the following command to debug:\n aws ec2 describe-images --image-ids "%s"' "$AMI_ID"
else
if ! aws ec2 deregister-image --image-id "$AMI_ID" > /dev/null; then
die 'image deregistration failed; run the following command to debug:\n aws ec2 deregister-image --image-id "%s"' "$AMI_ID"
fi
if ! aws ec2 delete-snapshot --snapshot-id "$SNAPSHOT_ID" > /dev/null; then
die 'snapshot deletion failed; run the following command to debug:\n aws ec2 delete-snapshot --snapshot-id "%s"' "$SNAPSHOT_ID"
fi
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment