Search code examples
ansiblejinja2

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.


Solution

  • 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