How to loop over a nested dictionary in ansible?

Viewed 840

How can I loop over this dictionary?

# nested dictionary to loop over:
  vars:
    commands:
      group1:
        cmd1:
          run: foo
        cmd2:
          run: bar
      group2:
        cmd3:
          run: zoo

# expected loop:
- group1, cmd1={...}
- group1, cmd2={...}
- group2, cmd4={...}

I tried using various combinations of dict2items and with_nested but so far I was not able to achieve that goal, and I would really want to avoid using loops with include tasks or writing a python module that does the flattening.

I still hope there is a pure-ansible way of doing it.

1 Answers

It's possible to loop tasks included by included_tasks. For example the file

shell> cat inner-loop.yml
- debug:
    msg: "{{ outer_item.key }}, {{ item.key }}={{ item.value }}"
  loop: "{{ outer_item.value|dict2items }}"

included from the task

    - include_tasks: inner-loop.yml
      loop: "{{ commands|dict2items }}"
      loop_control:
        loop_var: outer_item

gives

    "msg": "group1, cmd1={u'run': u'foo'}"
    "msg": "group1, cmd2={u'run': u'bar'}"
    "msg": "group2, cmd3={u'run': u'zoo'}"
Related