3

I have a j2 file that i want to edit and copy to my remote server (as apart of my ansible play). The file has several 3 variables indicated by braces {{ }}. How can I only target the 2nd variable named {{ bar }} and ignore the other 2 in the file so they're left alone and copied to my remote server? For example, my test.j2 file contains:

line 1 {{ foo }}
line 2 {{ bar }}
line 3 {{ foo2 }}

Can I explicitly address {{ bar }} variable in my ansible playbook? If so, how would i write it (syntactically) in my ansible playbook?

druffin
  • 163
  • 2
  • 15

3 Answers3

9

What follows isn't something I would recommend, but if you need to template only bar and nothing else (or if bar is always templated first before the rest), you can probably use the {% raw %} block:

{% raw %}line 1 {{ foo }}{% endraw %}
line 2 {{ bar }}
{% raw %}line 3 {{ foo2 }}{% endraw %}

Basically the idea is to mark non-bar variables as raw so that jinja doesn't template them.

bow
  • 2,503
  • 4
  • 22
  • 26
3

yet another alternative:

line 1 {{ '{{foo}}' }}
line 2 {{ bar }}
line 3 {{ '{{foo2}}' }}
Chris Maes
  • 35,025
  • 12
  • 111
  • 136
2

You can use the {% raw %} block as @bow mentions or there's also a shorthand for smaller chunks of code, it's shorter but not necessarily more readable than just using a raw block.

line 1 {{ '{{' }} foo {{ '}}' }}
line 2 {{ bar }}
line 3 {{ '{{' }} foo {{ '}}' }}

http://jinja.pocoo.org/docs/2.9/templates/#escaping

Nick Hammond
  • 11,228
  • 1
  • 19
  • 9