Home > Net >  Best way of looping over a list of dictionaries within a list of dictionaries in Ansible
Best way of looping over a list of dictionaries within a list of dictionaries in Ansible

Time:01-30

If I have this data structure:


blahblah:
  - name: firstdict
    touch:
      - file: name1
        type: file
      - file: name2
        type: directory
  - name: seconddict
    touch:
      - file: name3
        type: file

How can I loop over this to ensure each file exists and is of type type whilst handling the event that the touch value might not even be present?

I have tried:

- name: Blah
  file:
    path: "{{ item.1.file }}"
    state: "{{ item.1.type }}"
  with_subelements:
    - "{{ blahblah }}"
    - touch

It seems to work but fails if the touch key isn't present in the dictionary. Is there a way to provide a default empty list if touch isn't specified?

CodePudding user response:

Use the loop syntax instead of the with_subelements one.
Not only it is kind of recommended by Ansible, nowadays – see the notes in the "Loop" documentation page – it will also force you to use the subelements filter, and with it, discover its skip_missing parameter.

Given the task:

- debug:
    msg: "{{ item }}"
  loop: "{{ blahblah | subelements('touch', skip_missing=True) }}"
  loop_control:
    label: "{{ item.0.name }}"
  vars:
    blahblah:
      - name: first dict
        touch:
          - file: name1
          - file: name2
      - name: second dict
        touch:
          - file: name3
      - name: without touch

This would yield:

ok: [localhost] => (item=firstdict) => 
  msg:
  - name: firstdict
    touch:
    - file: name1
      type: file
    - file: name2
      type: directory
  - file: name1
    type: file
ok: [localhost] => (item=firstdict) => 
  msg:
  - name: firstdict
    touch:
    - file: name1
      type: file
    - file: name2
      type: directory
  - file: name2
    type: directory
ok: [localhost] => (item=seconddict) => 
  msg:
  - name: seconddict
    touch:
    - file: name3
      type: file
  - file: name3
    type: file
  • Related