Tuesday, March 15, 2022

[SOLVED] Find and remove outdated AMIs in AWS

Issue

I need to remove a list of outdated Ami's in AWS. But first I require to verifying are there any place still using those Ami's. Is there an efficient way to find it out.


Solution

First, you need to define "Outdated AMIs", it can be the creation date or something else. But here is the script that will list Instance ID along with AMI details that used by particular instance in particular region. By default it will look into default region.

#Get list of EC2 instance
echo "Getting EC2"
EC2_LIST=$(aws ec2 describe-instances --query 'Reservations[].Instances[].{InstanceId:InstanceId}' --output text | tr '\n' ' ')
#Get list of AMI used by ec2
echo "Getting AMI"
LIST_AMI_ID=$(aws ec2 describe-instances --query 'Reservations[].Instances[].{ImageId:ImageId,InstanceId:InstanceId}' --output text | tr '\n' ' ')

EC2_LIST_ARRAY=($EC2_LIST)
LIST_AMI_ID_ARRAY=($LIST_AMI_ID)

for index in ${!LIST_AMI_ID_ARRAY[*]}; do

echo "Get details for AMI ${LIST_AMI_ID_ARRAY[$index]}"
#Get details of AMI
AMI_DETAILS=$(aws ec2 describe-images --image-ids ${LIST_AMI_ID_ARRAY[$index]} --query 'Images[].{CreationDate:CreationDate,Tags:Tags[]}')
echo "Instance having ID ${EC2_LIST_ARRAY[$index]} using  AMI ID ${LIST_AMI_ID_ARRAY[$index]}  Details: $AMI_DETAILS"
done

output

Get details for AMI ami-0219162cf838b3455
Instance having ID i-0ceb0dfa197fd7455 using  AMI ID ami-0219162cf838b3455  Details: [
    {
        "CreationDate": "2019-10-22T05:17:46.000Z",
        "Tags": [
            {
                "Key": "Base_AMI_Name",
                "Value": "ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-20191021"
            },
            {
                "Key": "OS_Version",
                "Value": "Ubuntu"
            },
            {
                "Key": "Release",
                "Value": "Latest"
            },
            {
                "Key": "Name",
                "Value": "postgres"
            },
            {
                "Key": "Scope",
                "Value": "database"
            }
        ]
    }
]

aws-cli-cheatsheet



Answered By - Adiii
Answer Checked By - Willingham (WPSolving Volunteer)