45

The template looks like this:

solr.replication.master=
    {% if ansible_eth0.ipv4.address == servermaster.eth0 %}
        false
    {% else %}
        true
    {% endif %}

solr.replication.slave=false

And the output should look like this:

solr.replication.master=true
solr.replication.slave=false

What I am actually getting is:

solr.replication.master=truesolr.replication.slave=false

I understand that Jinja2 strips whitespace, and that ansible is probably configuring this by default. But it does not seem to honor -/+ whitespace tags.

Is there a way to force a line break?

0

5 Answers 5

37

Add the following line to your template at first position:

#jinja2: trim_blocks:False
5
  • Where did you find this? Documentation reference would be great because I can't find it and I think I need something very similar but not this exactly
    – byoungb
    Mar 30, 2017 at 18:34
  • This results in every line that contains only conditionals being printed as a blank line. Might be ok for some, but... May 12, 2017 at 18:22
  • @byoungb See this section of the docs, and also, the source for the environment options may be of use. Oct 26, 2019 at 17:23
  • 1
    Yeah actually I meant to ask where it was documented that you could set jinja2 environment variables as comments at the top of templates.
    – byoungb
    Oct 29, 2019 at 13:27
  • documentation about such comment in ansible template: docs.ansible.com/ansible/latest/collections/ansible/builtin/…
    – simohe
    Oct 6, 2020 at 9:56
21

I had the same issue. I solved it by adding

{{''}}

to the end of the line, for example:

solr.replication.master={% if ansible_eth0.ipv4.address == servermaster.eth0 %}false{% else %}true{% endif %}{{''}}

This inserts an empty string literal, with the side effect that whitespace is not stripped.

8

As you mentioned -/+ whitespace tags are not honored, nor are line macros enabled (at least not %% or # or ##).

trim_blocks is enabled in ansible. The only thing that I found that does work, is that trim_blocks ignores only the first newline

For your example, just adding an extra newline should be sufficient

solr.replication.master={% if ansible_eth0.ipv4.address == servermaster.eth0 %}false{% else %}true{% endif %}

solr.replication.slave=false
2

I believe using a ternary filter might help.

solr.replication.master={{ (ansible_eth0.ipv4.address == servermaster.eth0) | ternary('false', 'true') }}
solr.replication.slave=false
1

As workaround you can add to your template

{% raw %}{% endraw %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.