1

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 2

2

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"
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Yes that was what I meant, thanks. Quite simple.
I downvoted because that I could modify my answer instead of being directly downvoted. And originally the intention was to deprecate it. sorry for any confusion. I'll update my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.