lonix
lonix

Reputation: 20967

Inline comment in ansible jinja2 template

My docker .env file is created from a jinja2 template. I'm using {# ... #} for comments.

It has this:

FOO={{BAR}}        {# blah blah blah #}
SOMETHING=2

I expect it to render:

FOO=1
SOMETHING=2

But it actually renders:

FOO=1    SOMETHING=2

Upvotes: 0

Views: 2645

Answers (2)

Jon Musselwhite
Jon Musselwhite

Reputation: 1821

Update for 2021 (version 3.0.x)


Use plus sign (+) in tag

As @mdaniel pointed out, there are a few ways to adjust Jinja2's whitespace behavior, but a new option has appeared in 3.0.x's documentation that I believe is easiest way to solve the problem:

... you can manually disable the trim_blocks behavior by putting a plus sign (+) at the end of a block:

<div>
  {% if something +%}
    yay
  {% endif %}
</div>

Therefore, your specific problem should be easily solved by the insertion of a single plus symbol:

FOO={{BAR}}        {# blah blah blah +#}
SOMETHING=2

And if you want to remove the whitespace which would appear between the variable and the comment, explicitly remove it with a minus symbol:

FOO={{BAR}}        {#- blah blah blah +#}
SOMETHING=2

Use trim_blocks parameter

Since this question tags Ansible, I should point out that you can also modify the behavior by setting the trim_blocks parameter of the ansible.builtin.template module. This has been part of Ansible since version 2.4. The default is yes, but you can set it to no to achieve the desired result.


Hopefully this will help other people who find this question seeking a similar solution.

Upvotes: 4

mdaniel
mdaniel

Reputation: 33221

Jinja2 strips trailing newlines after blocks, as described in the fine manual

You can influence that behavior in at least 3 ways:

  1. Don't use end-of-line comments (since they will end with #}\n and thus jinja2 will eat the \n)
  2. Force the character after the jinja2 block to be a non-newline character (such as #} \n, although that will make git and some editors mad, since it is considered trailing whitespace
  3. If this is happening in a template: context, you can turn off trim_blocks: no; in certain contexts, you can do that inside the template itself, too, via a #jinja2:trim_blocks:False header in the template, as described by that template: documentation page

Upvotes: 2

Related Questions