Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
List all AMIs not in use by EC2 instances or AutoScalingGroups
#!/bin/bash
function our_amis() {
aws ec2 describe-images --owners self --query 'Images[*].ImageId' | jq -Sr '.[]'
}
function ec2_amis() {
aws ec2 describe-instances --query 'Reservations[*].Instances[*].ImageId' | jq -Sr '. | flatten | unique | .[]'
}
function asg_amis() {
for t in $(aws autoscaling describe-auto-scaling-groups --query 'AutoScalingGroups[*].[LaunchTemplate || MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification]' | jq -r '.[][] | (.LaunchTemplateId + ";" + .Version)'); do
t=(${t//;/ }); aws ec2 describe-launch-template-versions --launch-template-id ${t[0]} --versions ${t[1]//$/\$} --query 'LaunchTemplateVersions[*].LaunchTemplateData.ImageId' | jq -r '.[]'
done | sort -u
}
function in_use_amis() {
{ ec2_amis & asg_amis; } | sort -u
}
comm -23 <(our_amis) <(in_use_amis)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment