MrJuju23
MrJuju23

Reputation: 23

Create a list of dictionaries from another list and a static value, using Jinja2

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.

Upvotes: 2

Views: 1739

Answers (2)

Frenchy
Frenchy

Reputation: 17007

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

Upvotes: 1

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39119

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

Upvotes: 1

Related Questions