Posted on Leave a comment

Ansible loop over nested dictionary subelements – list object has no attribute

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.

 name: test1-ansible
 folder: ansible
 cpus: 1
 sockets: 1
 memory: 64
  - 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
    - name: loop over nested
        msg: '"{{ item.1.disksize }}"  "{{ item.1.disktype }}"'
      loop: "{{ vms| subelements('disk') }}" 

By performing a debug print, we can successfully get the nested keys values.