Home > Blockchain >  jinja2 - get rid of empty lines when variables are not defined
jinja2 - get rid of empty lines when variables are not defined

Time:04-05

I always get a newline when a variable is not defined in the following example:

Playbook:

- name: testplaybook jinja2
  hosts: all
  gather_facts: no
  vars:
    testvalue1: "A"
    testvalue2: "B"
    testvalue4: "D"
    testvalue5: "E"

  tasks:

    - name: test jinja2 template
      local_action:
        module: template
        src: testtemplate2.xml.j2
        dest: testtemplate2_output.xml
        trim_blocks: no

testtemplate2.xml.j2:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <instances>
    <testinstance staticvaluex=X
      staticvaluey=Y
      staticvaluez=Z
{% if testvalue1 is defined %}      value1="{{ testvalue1 }}"{% endif %}
{% if testvalue2 is defined %}      value2="{{ testvalue2 }}"{% endif %}
{% if testvalue3 is defined %}      value3="{{ testvalue3 }}"{% endif %}
{% if testvalue4 is defined %}      value4="{{ testvalue4 }}"{% endif %}
{% if testvalue5 is defined %}      value5="{{ testvalue5 }}"{% endif %}
    />
  </instances>
</configuration>

In the example we don't specify testvalue3 so the output testtemplate2_output.xml contains a newline:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <instances>
    <testinstance staticvaluex=X
      staticvaluey=Y
      staticvaluez=Z
      value1="A"
      value2="B"

      value4="D"
      value5="E"
    />
  </instances>
</configuration>

How can I get rid of this new line?

I tried a lot with {%- or %} or trim_blocks etc. but nothing seems to work. Of course this should then work with any of these lines because any of these variables could be empty and there must not be a newline.

CodePudding user response:

Using this j2 with this playbook does the job:

  tasks:
    - name: test jinja2 template
      local_action:
        module: template
        src: testtemplate2.xml.j2
        dest: testtemplate2_output.xml

file j2

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <instances>
    <testinstance staticvaluex=X
      staticvaluey=Y
      staticvaluez=Z
{%- if testvalue1 is defined %}      
      value1="{{ testvalue1 }}"
{% else %}

{% endif %}
{% if testvalue2 is defined %}
      value2="{{ testvalue2 }}"
{% endif %}
{% if testvalue3 is defined %}
      value3="{{ testvalue3 }}"
{% endif %}
{% if testvalue4 is defined %}
      value4="{{ testvalue4 }}"
{% endif %}
{% if testvalue5 is defined %}
      value5="{{ testvalue5 }}"
{% endif %}
    />
  </instances>
</configuration>

result:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <instances>
    <testinstance staticvaluex=X
      staticvaluey=Y
      staticvaluez=Z      
      value1="A"
      value2="B"
      value4="D"
      value5="E"
    />
  </instances>
</configuration>
  • Related