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' %}
An Ansible-specific twist (which newer versions of Ansible warn you about) is that conditional statements are implicitly a Jinja context, so you rarely want to include Jinja delimiters in them.
Example playbook:
- hosts: localhost
vars:
foo: bar
bar: false
baz: example.com
tasks:
- debug:
msg: Heyla
when: foo
- debug:
msg: La hey
when: "{{ foo }}"
- debug:
msg: Wa hey
when: "{{ baz }}"
Output:
PLAY [localhost] ***************************************************************
TASK [debug] *******************************************************************
ok: [localhost] =>
msg: Heyla
TASK [debug] *******************************************************************
skipping: [localhost]
TASK [debug] *******************************************************************
fatal: [localhost]: FAILED! =>
msg: |-
The conditional check '{{ baz }}' failed. The error was: error while evaluating conditional ({{ baz }}): 'example' is undefined
The error appears to be in 'test.yml': line 16, column 7, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- debug:
^ here