Ansible: conditional statements should not include jinja2 templating delimiters such as {{ }} or {% %}

Viewed 5888

Can someone help me in understanding and resolving it

 - name: Copying file to sever2
    fetch:
      src: /tmp/
      dest: /u0/test/
    when:
      "{{ inventory_hostname == 'testdb' }}"
2 Answers

In your case, you should use when condition without Jinja delimiters.

Example:

when: inventory_hostname == 'testdb'

Detailed explanation:

Jinja template delimiters are used when variable interpolation is required in context of text and templates. This tells Ansible to use the value of the variable instead of the variable name.

  • Consider everything as text unless told otherwise (with delimiters)

Example:

  vars:
    fav_tool: Ansible

  tasks:
  - debug:
      msg: "I like fav_tool"

This will output:

"msg": "I like fav_tool"

This is not what I wanted, I wanted to display "I like Ansible". So then I have to "tell" ansible to use the value of fav_tool.

  - debug:
      msg: "I like {{ fav_tool }}"

Similarly we use Jinja template delimiters in templates. Where we want to separate the variable, and expressions from text.

Example template such as below:

if fav_tool == 'Ansible'
I like Ansible
endif

... will result in exactly the same text without evaluating:

if fav_tool == 'Ansible'
I like Ansible
endif

However, when we use Jinja delimiters:

{% if fav_tool == 'Ansible' %}
I like Ansible
{% endif %}

It will result in:

I like Ansible

When we use conditions such as when:, we don't need delimiters as the conditionals will automatically interpolate the variable to value.

  • Consider everything as variables and expressions unless told otherwise (with '')

Example:

The case is reversed here and whatever is not enclosed in single-quotes is automatically evaluated. Only 'Ansible' is considered as text here (not evaluated).

  vars:
    fav_tool: Ansible

  tasks:
  - debug:
      msg: "Ansible rocks!"
    when: fav_tool == 'Ansible'

It worked for me with

    when:
     (inventory_hostname in groups['testdb'])
Related