Search code examples
ansiblejinja2

jinja2 templating empty or filled list to yaml


I want to Jinja2 template a config file in jinja2 with ansible:

Jinja2 Yaml:

test_dict:
  - index_patterns: {% if not test_list -%}[]{% else %}
    {% for ip in opensearch_index_patterns -%}
    - {{ ip }}
    {% endfor -%}
    {% endif %}
    next_param: ""

Playbook:

- name: Test2
  hosts: 127.0.0.1
  tasks:
   - name: stuff
     vars:
       test_list: []
     template:
       src: path/to/jinja2file.yml.j2
       dest: path/to/result.yml
       trim_blocks: false

If the list is filled, the result is as I want it:

test_list:
  - test1
  - test2
test_dict:
  - index_patterns: 
    - test1
    - test2
    next_param: ""

but if its empty, I get:

test_dict:
  - index_patterns: []next_param: ""

Is there a way to have next_param in a newline here without breaking the structure?


Solution

  • You can add a newline after []:

    test_dict:
      - index_patterns: {% if not test_list -%}[]
    {% else %}
        {% for ip in opensearch_index_patterns -%}
        - {{ ip }}
        {% endfor -%}
        {% endif %}
        next_param: ""