Help with converting a dictionary into a list (jinja2)

Hello,

seeking help with the following issue. So far I’ve only dealt with flat structures in ansible but this time I have the following:

firewalld_zones:
  xxx:
    services:
      - sshd
      - chromecast
    sources:
      - 1.1.1.1/32
  yyy:
    services:
      - sshd
      - h5ai
      - apache
    sources:
      - 1.2.3.4/32
      - 5.6.7.8/32

What I need to do is create a task for every service inside every zone. I am able to achieve this using jinja2:

- name: Show zone -> service mapping
  debug:
    msg: "{{ item[0] }} => {{ item[1] }}"
  loop: >
    {%- set data = [] -%}
    {%- for zone in firewalld_zones -%}
    {%- for service in firewalld_zones.get(zone).services -%}
    {{- data.append([zone, service]) -}}
    {%- endfor -%}
    {%- endfor -%}
    {{ data }}

But I highly doubt this is a way how this problem should be treated (too much lines, difficult to read). Could someone please point me at the right direction?

Thanks, jose

This works.

---
# jose_riha-subelements.yml
- name: Testing subelements
  hosts: localhost
  gather_facts: false
  vars:
    firewalld_zones:
      xxx:
        services:
          - sshd
          - chromecast
        sources:
          - 1.1.1.1/32
      yyy:
        services:
          - sshd
          - h5ai
          - apache
        sources:
          - 1.2.3.4/32
          - 5.6.7.8/32
  tasks:
    - name: Loop over firewall_zones pairing subelement services
      ansible.builtin.debug:
        msg: "{{ item.0.key }} -> {{ item.1 }}"
      loop: "{{ firewalld_zones | dict2items | subelements('value.services')    }}"

which produces:

TASK [Loop over firewall_zones pairing subelement services] ************************************************************************************************************
ok: [localhost] => (item=[{'key': 'xxx', 'value': {'services': ['sshd', 'chromecast'], 'sources': ['1.1.1.1/32']}}, 'sshd']) => {
    "msg": "xxx -> sshd"
}
ok: [localhost] => (item=[{'key': 'xxx', 'value': {'services': ['sshd', 'chromecast'], 'sources': ['1.1.1.1/32']}}, 'chromecast']) => {
    "msg": "xxx -> chromecast"
}
ok: [localhost] => (item=[{'key': 'yyy', 'value': {'services': ['sshd', 'h5ai', 'apache'], 'sources': ['1.2.3.4/32', '5.6.7.8/32']}}, 'sshd']) => {
    "msg": "yyy -> sshd"
}
ok: [localhost] => (item=[{'key': 'yyy', 'value': {'services': ['sshd', 'h5ai', 'apache'], 'sources': ['1.2.3.4/32', '5.6.7.8/32']}}, 'h5ai']) => {
    "msg": "yyy -> h5ai"
}
ok: [localhost] => (item=[{'key': 'yyy', 'value': {'services': ['sshd', 'h5ai', 'apache'], 'sources': ['1.2.3.4/32', '5.6.7.8/32']}}, 'apache']) => {
    "msg": "yyy -> apache"
}
4 Likes

Thank you very much. That’s exactly what I was looking for.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.