Skip to content

Instantly share code, notes, and snippets.

@johanforssell
Created April 29, 2024 08:04
Show Gist options
  • Save johanforssell/c6167ab9aa842bd47ebf9fb64a946eb4 to your computer and use it in GitHub Desktop.
Save johanforssell/c6167ab9aa842bd47ebf9fb64a946eb4 to your computer and use it in GitHub Desktop.
Find all of your own AMIs which are not in use by any EC2 instance, nor are a "backup"
#!/usr/bin/env bash
# Find your AMIs which are not in use by any EC2 instance.
# Filter by a keyword; defaults to removing 'backup'.
# Set AWS credentials and region as normal.
# Remove AMIs with this keyword in the name
FILTERED_KEYWORD="backup"
aws ec2 describe-instances --query 'Reservations[*].Instances[*].ImageId' --output text | sort > /tmp/aws_ec2_ami.all
aws ec2 describe-images --owners self --query 'Images[*].[ImageId, Name]' --output text | grep -iv $FILTERED_KEYWORD | awk '{print $1}' | sort > /tmp/aws_ec2_ami.used
# Find out which region we're in
CURRENT_REGION=$(aws ec2 describe-availability-zones --output text --query 'AvailabilityZones[0].[RegionName]')
echo ''
echo "## AMI's not used by any EC2 instance in '$CURRENT_REGION':"
echo ''
comm -1 -3 /tmp/aws_ec2_ami.all /tmp/aws_ec2_ami.used
rm /tmp/aws_ec2_ami.all
rm /tmp/aws_ec2_ami.used
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment