Ansible loop array within dictionary structure

Viewed 68

I have ansible version 2.9.6 and the following structure:

  certificates:
    example1:
      - sub1.example1.org
      - sub2.example1.org
    example2:
      - sub1.example2.org
      - sub2.example2.org
    example3:
      - sub3.example3.org

Now I want to loop through the dictionary to get the name (key) of the certificate and then through the array to get the name of the domains to build a string out of it which is then used to create the certificates.

I did not archive what I wanted so far. I tried with dict2items to get the name and the item (array) but how to proceed from here?

The next I tried with with_subelement but the I get the error that item is undefined.

- name: with_dict -> loop (option 1)
  ansible.builtin.debug:
    msg: "Key: {{ item.key }} ###"
  with_subelements: 
    - "{{ certificates }}"
    - "{{item.1}}"

How can I access the list items then?

Thanks and Best Regards

MG

2 Answers

With Loop instead of the traditional way using with_subelements:

    - name: with_subelements -> loop
      debug:
        msg: "{{ item.0.key }} {{ item.1 }}"
      loop: "{{ certificates | dict2items | subelements('value') }}"

Adding New Notation:

    - name: with_subelements -> loop
      debug:
        msg: "{{ item[0]['key'] }} {{ item[1] }}"
      loop: "{{ certificates | dict2items | subelements('value') }}"

gives (abridged)

TASK [with_subelements -> loop]
    "msg": "example1 sub1.example1.org"
    "msg": "example1 sub2.example1.org"
    "msg": "example2 sub1.example2.org"
    "msg": "example2 sub2.example2.org"
    "msg": "example3 sub3.example3.org"

For example

    - debug:
        msg: "{{ item.0.key }} {{ item.1 }}"
      with_subelements:
        - "{{ certificates|dict2items }}"
        - value

gives (abridged)

  msg: example1 sub1.example1.org
  msg: example1 sub2.example1.org
  msg: example2 sub1.example2.org
  msg: example2 sub2.example2.org
  msg: example3 sub3.example3.org
Related