0

I'm using Ansible to provision AWS EC2 instances with the Amazon.Aws collection. On the cli, if I want to get the latest Amazon Linux 2 AMI I may run something like this:

$ aws ec2 describe-images \
      --region us-east-1 \
      --owners amazon \
      --query 'reverse(sort_by(Images, &CreationDate))[:1]' \
      --filters 'Name=name,Values=amzn2-ami-hvm-2.0.*-x86_64-gp2'

How do I make an equivalent query using Ansible's amazon.aws collection?

The amazon.aws.ec2_ami_info module seems to do what I want, but the provided example in the docs makes it seem like the lookup requires an OwnerId.

- name: Gather a list of all Amazon Linux \2 AMIs
  amazon.aws.ec2_ami_info:
    owners: 137112412989
    filters:
      name: amzn2-ami-hvm-*-x86_64-gp2

The OwnerId has to be retrieved with a cli command, like this:

$ aws ec2 describe-images \
      --region us-east-1 \
      --owners amazon \
      --filters 'Name=name,Values=amzn2-ami-hvm-2.0.*-x86_64-gp2' \
      --query 'reverse(sort_by(Images, &CreationDate))[:1].OwnerId' \
      --output text
137112412989

The problem is, I want to run that playbook on a node that doesn't have the awscli binary. I also don't want to hardcode the OwnerId.

1 Answers1

0

There were two missing peices - extracting the element with the most recent creation time, and specifying the owner using a name rather than the OwnerId. Here's a working solution.

- name: 'Find the latest Amazon Linux 2 AMI'
  block:
    - name: 'Get all Amazon Linux 2 AMIs'
      amazon.aws.ec2_ami_info:
        owners:
          - amazon
        filters:
          name: amzn2-ami-hvm-*-x86_64-gp2
          architecture: x86_64
          block-device-mapping.volume-type: gp2
          virtualization-type: hvm
          register: amis
      - name: Extract the most recently created AMI from the list
        debug:
          msg: "{{ amis.images[-1].image_id }}"
        register: latest_amzl2_ami
Tyler2P
  • 2,324
  • 26
  • 22
  • 31