Reputation: 339
I am trying to find a AWS Snapshot associated with AMI.
I am cleaning up my AMI list. After deregistering 2 AMI I have checked snapshot count its not reducing any reason behind this?
How can delete snapshot associated with AMI automatically when I am deleting AMI?
Upvotes: 4
Views: 7522
Reputation: 771
Two options these days:
Select all snapshots in the Console UI and then delete. It will successfully delete the ones that have no AMI and throw an error/do nothing for the others.
I like to list all snapshots (aws ec2 describe-snapshots) and then find the Description that contains the AMI ID you're looking for. All of my AMIs have something like Created by CreateImage(i-022609661e8f823b0) for ami-0dc3221b374ff156f
for example. This can be scripted:
set -aexo pipefail
REGIONS_TO_REMOVE_FROM=(
us-east-2
us-west-2
eu-central-1
eu-west-1
eu-west-2
eu-west-3
eu-north-1
)
AMI_NAME="${1}"
[[ -n "${AMI_NAME}" ]] || (echo "Missing AMI NAME as ARG1" && exit 1)
for TARGET_REGION in ${REGIONS_TO_REMOVE_FROM[*]}; do
AMI_ID="$(aws ec2 describe-images --region ${TARGET_REGION} \
--filters "Name=name,Values=${AMI_NAME}" "Name=state,Values=available" \
--query "sort_by(Images, &CreationDate)[-1].[ImageId]" \
--output "text")"
[[ -z "${AMI_ID}" || "${AMI_ID}" == "None" ]] && echo "missing source AMI..." && continue
aws ec2 deregister-image --region "${TARGET_REGION}" --image-id "${AMI_ID}"
SNAPSHOT_ID="$(aws ec2 describe-snapshots --region ${TARGET_REGION} --query "Snapshots[?Description!=null && contains(Description, '${AMI_ID}')]" | jq -r '.[0] | .SnapshotId')"
[[ -z "${SNAPSHOT_ID}" || "${SNAPSHOT_ID}" == "None" ]] && (exit 2)
aws ec2 delete-snapshot --region "${TARGET_REGION}" --snapshot-id "${SNAPSHOT_ID}"
done
Upvotes: 0
Reputation: 948
When you deregister an Amazon EBS-backed AMI, it doesn't affect the snapshot that was created for the root volume of the instance during the AMI creation process. You'll continue to incur storage costs for this snapshot. Therefore, if you are finished with the snapshot, you should delete it.
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/deregister-ami.html
And for writing some automation script, which can auto delete snapshots when you are deleting the AMI, you can have a look on following:
https://serverfault.com/questions/611831/find-all-snapshots-created-by-ami-where-ami-is-deleted
https://www.yobyot.com/aws/deregister-an-aws-ami-and-remove-associated-s3-snapshots/2014/10/30/
Upvotes: 1