Introduction

Ansible is a powerful automation tool that allows you to manage and configure servers and applications using simple YAML-based playbooks. One of the fundamental elements in Ansible playbooks is the 'when' clause, which is used to control the flow of tasks based on specific conditions. However, it's crucial to understand that when conditions are always templated, Ansible enforces a specific structure for these expressions to avoid errors and issues. In this article, we will explore Ansible Error 102, "No Jinja2 in when," and how to work with 'when' conditions properly using [Ansible-Lint](/articles/ansible-lint).

The 'when' Clause in Ansible

The 'when' clause is an essential feature in Ansible playbooks, allowing you to control the execution of tasks based on specific conditions. These conditions determine whether a task should run or be skipped. To specify conditions, you use the 'when' keyword followed by an expression, and Ansible evaluates this expression to determine if the task should be executed.

Understanding the Error

Ansible Error 102, "No Jinja2 in when" occurs when there is a Jinja2 template error within a 'when' condition. Jinja2 is the templating engine used by Ansible to process variables and expressions. The error message signifies that the 'when' condition contains a Jinja2 expression that is improperly formatted or missing necessary brackets.

Example playbook:

``yaml

---

  • name: Ensure production environment is configured

hosts: all

vars:

production: true

tasks:

- name: Ensure a task runs only in the production environment

ansible.builtin.debug:

msg: "This is a production task"

when: "{{ production }}"

`

Output:

`bash

WARNING Listing 2 violation(s) that are fatal

jinja[spacing]: Jinja2 spacing could be improved: {{ production }} -> production (warning)

102.yml:7 Task/Handler: Ensure a task runs only in the production environment

no-jinja-when: No Jinja2 in when.

102.yml:7 Task/Handler: Ensure a task runs only in the production environment

Read documentation for instructions on how to ignore specific rule violations.

Rule Violation Summary

count tag profile rule associated tags

1 jinja[spacing] basic formatting (warning)

1 no-jinja-when basic deprecations

Failed: 1 failure(s), 1 warning(s) on 1 files. Last profile that met the validation criteria was 'min'.

`

Correcting the 'when' Condition

To avoid Ansible Error 102, you need to ensure that your 'when' condition adheres to the following guidelines:

1. Raw Jinja2 Expression: The 'when' clause should contain a raw Jinja2 expression without double curly braces {{… }} or statement blocks {% … %}. Here's an example of a correct 'when' condition:

`yaml

when: var_service == 'httpd'

``

2. Using the 'vars' Lookup: To get a variable with a dynamic name within a 'when' condition, you should use the 'vars' lookup. The 'vars' l