Search code examples
dictionaryansiblejinja2

Iterate nested lists in dictionary


Given the dictionary

sudoers_include:
  sudofile1:
    privileges:
      - name: "%technodrome"
        paths: 
          - "ALL=(ALL) NOPASSWD: ALL"    

The task

- name: gen /etc/sudoers.d file
  template:
    src: sudoers_d_file.j2
    dest: "/etc/sudoers.d/{{ item.key }}"
  loop: "{{ sudoers_include | dict2items }}"

and the template

shell> cat sudoers_d_file.j2
{% for item in item.value.privileges | default([]) %}
{{ item.name }} {{ item.paths }}
{% endfor %}

give

shell> cat /etc/sudoers.d/sudofile1
%technodrome ['ALL=(ALL) NOPASSWD: ALL']

I should get

%technodrome ALL=(ALL) NOPASSWD: ALL

Solution

  • Iterate also the paths

    {% for item in item.value.privileges | default([]) %}
    {% for i in item.paths %}
    {{ item.name }} {{ i }}
    {% endfor %}
    {% endfor %}
    

    (not tested)