Jinja FAQ: Nested Moustaches?
If you’re already in a Jinja statement or expression, you should not use a second set of delimiters to set off expressions.
Wrong:
{{ foo[{{ bar }}] }}
{{ hostvars['{{ 'myhost-' + {{ foo }}']['bar'] }}
{{ '{{ foo }}' if bar else 'baz' }}
{% set foo == "{{ bar }}foo" %}
Right:
{{ foo[bar] }}
{{ hostvars['myhost-' ~ foo]['bar'] }}
{{ foo if bar else 'baz' }}
{% set foo = bar ~ 'foo' %}
Conditionals
An Ansible-specific twist is that conditional statements are implicitly a Jinja context, so you rarely want to include Jinja delimiters in them.
- hosts: localhost
vars:
foo: bar
bar: false
baz: example.com
tasks:
- debug:
msg: Heyla
when: foo is truthy
- debug:
msg: La hey
when: "{{ foo }}"
- debug:
msg: Wa hey
when: "{{ baz }}"
TASK [debug] ******************************************************************* ok: [localhost] => msg: Heyla TASK [debug] ******************************************************************* skipping: [localhost] TASK [debug] ******************************************************************* [ERROR]: Task failed: Error while evaluating conditional: 'example' is undefined Task failed. Origin: test.yml:15:7 13 when: "{{ foo }}" 14 15 - debug: ^ column 7 <<< caused by >>> Error while evaluating conditional. Origin: test.yml:17:13 15 - debug: 16 msg: Wa hey 17 when: "{{ baz }}" ^ column 13 <<< caused by >>> 'example' is undefined Origin: test.yml:5:10 3 foo: bar 4 bar: false 5 baz: example.com ^ column 10 fatal: [localhost]: FAILED! => msg: 'Task failed: Error while evaluating conditional: ''example'' is undefined'