Sometimes it could be tricky in Ansible to loop over a nested key-value list. Take for example the below dictionary which includes a nested list of disks. The upper element of the .yml file is vms which includes name, folder, cpus, sockets, memory and disk.
The disk element consists of disksize and disktype. This .yml file has been created on a previous post which explains how to automatically provision VMware servers.
vms: name: test1-ansible folder: ansible cpus: 1 sockets: 1 memory: 64 disk: - disksize: 64 disktype: thin - disksize: 100 disktype: thin
If you try to loop over this list you will probably get an error like list object has no attribute.
With the subelements command you can loop over your main list (vms) and access your nested one (disk) with a different index.
In order to retrieve the vm name you should use item.0. The nested values are placed under item.1
--- - name: test playbook hosts: localhost vars_files: vms.yml tasks: - name: loop over nested debug: msg: '"{{ item.1.disksize }}" "{{ item.1.disktype }}"' loop: "{{ vms| subelements('disk') }}"
By performing a debug print, we can successfully get the nested keys values.