Skip to content

Instantly share code, notes, and snippets.

@ilpianista
Created April 22, 2022 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilpianista/a8dfe8f7042d61abb8524571be910403 to your computer and use it in GitHub Desktop.
Save ilpianista/a8dfe8f7042d61abb8524571be910403 to your computer and use it in GitHub Desktop.
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