groupby the list packages.results by name and create the dictionary my_packages
my_packages: "{{ dict(packages.results|groupby('name')) }}"
Then, the below template
- debug:
msg: |
{% for name,versions in my_packages.items() %}
{% set max_ver=versions|map(attribute='version')|max %}
{% set p=versions|selectattr('version', '==', max_ver) %}
{{ name }}-{{ p.0.version }}-{{ p.0.release }}
{% endfor %}
gives what you want
msg: |-
adcli-0.8.2-12.el8
alsa-sof-firmware-1.8-1.el8
ansible-7.2.0-1.el8
authselect-1.2.2-3.el8
authselect-libs-1.2.2-3.el8
bash-4.4.20-2.el8
bind-export-libs-9.11.26-6.el8
binutils-2.30-108.el8
bpftool-4.18.0-348.2.1.el8_5
ca-certificates-2021.2.50-80.0.el8_4
centos-gpg-keys-8-3.el8
centos-linux-release-8.5-1.2111.el8
centos-linux-repos-8-3.el8
centos-logos-85.8-2.el8
...
Example of a complete playbook for testing
- hosts: foo
vars:
my_packages: "{{ dict(packages.results|groupby('name')) }}"
tasks:
- dnf:
list: updates
register: packages
- debug:
msg: |
{% for name,versions in my_packages.items() %}
{% set max_ver=versions|map(attribute='version')|max %}
{% set p=versions|selectattr('version', '==', max_ver) %}
{{ name }}-{{ p.0.version }}-{{ p.0.release }}
{% endfor %}
Q: "The error was: generator object has no element 0"
A: The problem might be an older version of Ansible. Try explicit conversion to list
{% set p=versions|selectattr('version', '==', max_ver)|list %}