List all AMIs not in use by EC2 instances or AutoScalingGroups
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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