Find Latest AMI in AWS

We need to fetch the latest AMI ID for Ubuntu 22.04. This will be used as the base image to create a custom AMI by Packer.

Fetching AMI ID

Create a class called Slice. This class is inside Python package called grid.

Project Structure
.
├── README.md
├── grid
│   ├── __init__.py
│   └── slice.py
├── requirements.txt
└── test_hive.py

The Slice class:

slice.py
import boto3
from datetime import datetime


class Slice:
    def __init__(self):
        self.ec2 = boto3.client('ec2')

    def get_latest_ami_id(self, source_ami_name, ami_owners):
        response = self.ec2.describe_images(
            Filters=[
                {
                    'Name': 'name',
                    'Values': [source_ami_name]
                },
                {
                    'Name': 'virtualization-type',
                    'Values': ['hvm']
                }
            ],
            Owners=ami_owners
        )

        if response['Images']:
            latest_image = max(response['Images'], key=lambda x: x['CreationDate'])
            creation_date = datetime.strptime(latest_image['CreationDate'], "%Y-%m-%dT%H:%M:%S.%fZ")
            formatted_date = creation_date.strftime("%Y-%m-%d")
            return latest_image['ImageId'], formatted_date
        else:
            return None, None

Create a Test Program

We will print the AMI ID and the creation date so that we can verify it manually from the AWS console. Create test_hive.py with:

test_hive.py
from grid.slice import Slice

wafer = Slice()

source_ami_name = "ubuntu/images/*ubuntu-jammy-22.04-amd64-server-*"
ami_owners = ["099720109477"]

latest_ami_id, creation_date = wafer.get_latest_ami_id(source_ami_name, ami_owners)

if latest_ami_id:
    print(f"Latest AMI ID: {latest_ami_id}")
    print(f"AMI Creation Date: {creation_date}")
else:
    print("No matching AMI found.")

Run the Program

Output:

AMI Details
Latest AMI ID: ami-053053586808c3e70
AMI Creation Date: 2024-03-26

You can also use Ansible playbook as discussed in Latest AMI for this task.