2

I need to create a list of dictionaries using only Jinja2 from another list, as input.
One key/value pair is static and always the same, the other changes value.

Input:

targets: ["abc", "qwe", "def"]

I know that the server will always be xyz.

Final

connections:
  - { "target": "abc", "server": "xyz" }
  - { "target": "qwe", "server": "xyz" } 
  - { "target": "def", "server": "xyz" } 

I tried this:

"{{ dict(targets | zip_longest([], fillvalue='xyz')) }}"

But, that just takes one for key and the other for value.

1
  • using only jinja2 is unclear.... Commented Apr 11, 2022 at 14:58

2 Answers 2

1

You were quite close.

But you'll need a product rather than a zip_longest to have the same element repeating for all the element of your targets list.

You were also missing a dict2items to close the gap and have the resulting list out of your dictionary.

Which gives the task:

- set_fact:
    connections: >-
      {{
        dict(targets | product(['xyz']))
        | dict2items(key_name='target', value_name='server')
      }}

Given the playbook:

- hosts: localhost
  gather_facts: no

  tasks:
    - set_fact:
        connections: >-
          {{
            dict(targets | product(['xyz']))
            | dict2items(key_name='target', value_name='server')
          }}
      vars:
        targets:
          - abc
          - qwe
          - def

    - debug:
        var: connections

This yields:

ok: [localhost] => 
  connections:
  - server: xyz
    target: abc
  - server: xyz
    target: qwe
  - server: xyz
    target: def
Sign up to request clarification or add additional context in comments.

Comments

1

just use set_fact with the right loop:

- name: testplaybook jinja2
  hosts: localhost
  gather_facts: no
  vars:
    targets: ["abc", "qwe", "def"]

  tasks:
    - name: DEFINE VARIABLE SPINE
      set_fact: 
        connections: "{{ connections | d([]) + [ {'target': item, 'server': _server} ] }}"
      loop: "{{ targets }}"
      vars:
        _server: xyz

    - name: display
      debug:
        var: connections

result:

connections:
- server: xyz
  target: abc
- server: xyz
  target: qwe
- server: xyz
  target: def

Comments

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.