Invoke-CleanupAMIsandSnapshots
#Run the Get-AGAMITags script and send the output to a csv file
Example:
Get-AGAMITags | Export-Csv <Path to save CSV>
#Filter the results to remove any AMI with a release version that should not be deleted and save the modified file as Filename-Filtered.csv before running the below script
#Open the filtered out CSV file
$imageList = Import-Csv <Path to Filtered CSV>
foreach ($image in $imageList)
{
$imageID = $image.imageid
$imageRegion = $image.Region
$ami = Get-EC2Image -Region $imageRegion -ImageId $imageID
$snapshots = @($ami.BlockDeviceMapping.ebs.snapshotid)
# Snapshots of root volumes cannot be deleted unless the AMI is deregistered first
Unregister-EC2Image -Region $imageRegion -ImageId $ami.ImageId
Write-Host $ami.ImageId "Unregistered"
foreach ($SnapshotID in $snapshots) {
# Delete leftover snapshots
Remove-EC2Snapshot -Region $imageRegion $SnapshotID -Force
Write-Host $SnapshotID "Removed"
} # End foreach $snapshots
}