- EC2 Image Builder: Build your golden VM images on AWS - Wed, Jan 19 2022
- Configuring DFS Namespaces for Amazon FSx for Windows file servers - Fri, Jan 7 2022
- AWS Systems Manager Session Manager: Securely connect EC2 instances - Wed, Dec 22 2021
Delete the AMI and its associated snapshots using the AWS Console
Navigate to the EC2 Console. On the left menu, choose Images > AMIs.
Select the AMI you want to remove, and click Actions.
Choose Deregister, then click Continue.
Note: Before you deregister the AMI, make sure you've copied its ID.
On the left menu, choose Elastic Block Store > Snapshots.
On the Snapshots search bar, search for the AMI ID you deregistered earlier. The snapshots are filtered, so that only the ones associated with this AMI are displayed.
Select the snapshots, click Actions, and choose Delete.
Note: If you tried to remove a root volume snapshot associated with an AMI before deregistering the AMI, you will get an error message that the snapshot is currently in use by an AMI.
Delete the AMI and its associated snapshots using bash and the AWS CLI
First, you need to retrieve the snapshots associated with the AMI using the following command:
Snapshots="$(aws ec2 describe-images --image-ids <Pass the image ID here> --region <Pass the region in which this AMI is located> --query 'Images[*].BlockDeviceMappings[*].Ebs.SnapshotId' --output text)"
Afterward, you can deregister the AMI using the following command:
aws ec2 deregister-image --image-id <Pass the image ID here>
Finally, you can remove all the snapshots associated with that AMI by running the following command:
for SNAPSHOT in $Snapshots ; do aws ec2 delete-snapshot --snapshot-id $SNAPSHOT; done
Delete the AMI and its associated snapshots using PowerShell
First, you need to retrieve the AMI and store it in a variable using the following cmdlet:
$ami = Get-EC2Image -ImageId <Pass the image ID here>
Then, you need to retrieve the snapshot IDs associated with this AMI and store them in an array using the following cmdlet:
$Snapshots = @($ami.BlockDeviceMapping.ebs.snapshotid)
Afterward, you can deregister the AMI using the following cmdlet:
Unregister-EC2Image -ImageId $ami.ImageId
Finally, you can remove all the snapshots associated with that AMI by running the following piece of code:
foreach ($Snapshot in $Snapshots) { Remove-EC2Snapshot $Snapshot }
Conclusion
In this article, we've gone through a step-by-step guide about how to delete an AMI and its associated snapshots. If you've got any further questions, please mention them in the comments.
Subscribe to 4sysops newsletter!
DISCLAIMER: This article represents my own viewpoints and not those of my employer, Amazon Web Services.