Retrieve Latest AMI ID

Create the Playbook

Create a playbook find_latest_ami.yml to get the latest Ubuntu 22.04 AMI ID.

find_latest_ami.yml
---
- name: Find Ubuntu 22.04 AMI ID
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Get AMI for Ubuntu 22.04
      amazon.aws.ec2_ami_info:
        filters:
          name: "ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"
          architecture: "x86_64"
          root-device-type: "ebs"
          virtualization-type: "hvm"
          state: "available"
        owners: "099720109477" # Canonical's AWS account ID
        sort: "creation_date"
        sort_order: "descending"
        sort_end: 1
      register: ami_info

    - name: Print the latest Ubuntu 22.04 AMI ID
      debug:
        msg: "The latest Ubuntu 22.04 AMI ID is {{ ami_info.images[0].image_id }}"

Run the Playbook

From the project root:

Ansible Playbook Command
$ ansible-playbook -i hosts experiments/find_latest_ami.yml

Trouble Shooting Issues

Connection Problem

Failed to connect to the host via ssh: ssh: connect to host localhost port 22: Connection refused.

Connection Error
PLAY [Find Ubuntu 22.04 AMI ID] 

TASK [Get AMI for Ubuntu 22.04] 
fatal: [localhost]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host localhost port 22: Connection refused", "unreachable": true}

PLAY RECAP 
localhost                  : ok=0    changed=0    unreachable=1    failed=0    skipped=0    rescued=0    ignored=0   

Change the connection parameter connection to local in the playbook:

find_latest_ami.yml
---
- name: Find Ubuntu 22.04 AMI ID
  hosts: localhost
  gather_facts: false
  connection: local

Run the playbook.

Unsupported Parameters

Error: Unsupported parameters for (amazon.aws.ec2_ami_info) module.

Unsupported Parameters Error
fatal: [localhost]: FAILED! => {"ansible_facts": {"discovered_interpreter_python": "/Library/Frameworks/Python.framework/Versions/3.12/bin/python3.12"}, "changed": false, "msg": "Unsupported parameters for (amazon.aws.ec2_ami_info) module: sort, sort_end, sort_order. Supported parameters include: access_key, aws_ca_bundle, aws_config, debug_botocore_endpoint_logs, describe_image_attributes, endpoint_url, executable_users, filters, image_ids, owners, profile, region, secret_key, session_token, validate_certs (access_token, aws_access_key, aws_access_key_id, aws_endpoint_url, aws_profile, aws_region, aws_secret_access_key, aws_secret_key, aws_security_token, aws_session_token, ec2_access_key, ec2_region, ec2_secret_key, ec2_url, executable_user, image_id, owner, s3_url, security_token)."}

Use Jinja2 filters to sort the images by creation date and select the last one.

find_latest_ami.yml
---
- name: Find Ubuntu 22.04 AMI ID
  hosts: localhost
  gather_facts: false
  connection: local
  tasks:
    - name: Get AMI for Ubuntu 22.04
      amazon.aws.ec2_ami_info:
        filters:
          name: "ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"
          architecture: "x86_64"
          root-device-type: "ebs"
          virtualization-type: "hvm"
          state: "available"
        owners: "099720109477"
      register: ami_info

    - name: Print the latest Ubuntu 22.04 AMI ID
      debug:
        msg: "The latest Ubuntu 22.04 AMI ID is {{ ami_info.images | sort(attribute='creation_date') | last }}"
Lastes AMI ID
TASK [Print the latest Ubuntu 22.04 AMI ID] 
ok: [localhost] => {
    "msg": "The latest Ubuntu 22.04 AMI ID is {'architecture': 'x86_64', 'creation_date': '2024-03-19T02:40:52.000Z', 'image_id': 'ami-0e21465cede02fd1e', 'image_location': 'amazon/ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20240319', 'image_type': 'machine', 'public': True, 'owner_id': '099720109477', 'platform_details': 'Linux/UNIX', 'usage_operation': 'RunInstances', 'state': 'available', 'block_device_mappings': [{'device_name': '/dev/sda1', 'ebs': {'delete_on_termination': True, 'snapshot_id': 'snap-03c5c9d209ae83c8b', 'volume_size': 8, 'volume_type': 'gp2', 'encrypted': False}}, {'device_name': '/dev/sdb', 'virtual_name': 'ephemeral0'}, {'device_name': '/dev/sdc', 'virtual_name': 'ephemeral1'}], 'description': 'Canonical, Ubuntu, 22.04 LTS, amd64 jammy image build on 2024-03-19', 'ena_support': True, 'hypervisor': 'xen', 'image_owner_alias': 'amazon', 'name': 'ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20240319', 'root_device_name': '/dev/sda1', 'root_device_type': 'ebs', 'sriov_net_support': 'simple', 'virtualization_type': 'hvm', 'boot_mode': 'uefi-preferred', 'deprecation_time': '2026-03-19T02:40:52.000Z', 'tags': {}}"
}

PLAY RECAP 
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Verify the AMI ID

You can verify that the AMI ID is correct by logging into the AWS console and searching for the AMI ID. Go to EC2 dashboard and click on the AMI Catalog. Select the Community AMIs tab and search for ami-0e21465cede02fd1e. You can see the creation date also matches.

You can also use AWS CLI to verify from the command line:

AWS CLI command
$ aws ec2 describe-images --image-ids ami-0e21465cede02fd1e --region us-east-1

Output:

{
    "Images": [
        {
            "Architecture": "x86_64",
            "CreationDate": "2024-03-19T02:40:52.000Z",
            "ImageId": "ami-0e21465cede02fd1e",
            "ImageLocation": "amazon/ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20240319",
            "ImageType": "machine",
            "Public": true,
            "OwnerId": "099720109477",
            "PlatformDetails": "Linux/UNIX",
            "UsageOperation": "RunInstances",
            "State": "available",
            "BlockDeviceMappings": [
                {
                    "DeviceName": "/dev/sda1",
                    "Ebs": {
                        "DeleteOnTermination": true,
                        "SnapshotId": "snap-03c5c9d209ae83c8b",
                        "VolumeSize": 8,
                        "VolumeType": "gp2",
                        "Encrypted": false
                    }
                },
                {
                    "DeviceName": "/dev/sdb",
                    "VirtualName": "ephemeral0"
                },
                {
                    "DeviceName": "/dev/sdc",
                    "VirtualName": "ephemeral1"
                }
            ],
            "Description": "Canonical, Ubuntu, 22.04 LTS, amd64 jammy image build on 2024-03-19",
            "EnaSupport": true,
            "Hypervisor": "xen",
            "ImageOwnerAlias": "amazon",
            "Name": "ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20240319",
            "RootDeviceName": "/dev/sda1",
            "RootDeviceType": "ebs",
            "SriovNetSupport": "simple",
            "VirtualizationType": "hvm",
            "BootMode": "uefi-preferred",
            "DeprecationTime": "2026-03-19T02:40:52.000Z"
        }
    ]
}