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.

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:

---
- 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:

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:
when: var_service == 'httpd'
  1. Using the ‘vars’ Lookup: To get a variable with a dynamic name within a ‘when’ condition, you should use the ‘vars’ lookup. The ‘vars’ lookup allows you to access variables by constructing their names dynamically. For example:
when: lookup('vars', 'batches_' ~ var_function | regex_replace('^httpd-batch-', ''))
Join 50+ hours of courses in our exclusive community
  1. Combining Conditions with Logical Operators: If you have multiple conditions that all need to be true (logical AND), you can specify them as a list. This improves readability and avoids Jinja2 template errors. For instance:
when:
  - var_service == 'httpd'
  - >-
    item.path | regex_replace(cron_regex_for_s2_deletion, '\1')
    not in lookup('vars', 'batches_' ~ var_function | regex_replace('^httpd-batch-', ''))    

Utilizing YAML Multiline Tricks

You can use some YAML multiline tricks to keep the ‘when’ condition on a single line, making it more compact and readable. This can also help avoid lint warnings from Ansible. For instance:

when: 
  - var_service == 'httpd' 
  - >-
    item.path | regex_replace(cron_regex_for_s2_deletion, '\1') 
    not in lookup('vars', 'batches_' ~ var_function | regex_replace('^httpd-batch-', ''))    

Conclusion

Understanding Ansible Error 102, "No Jinja2 in when", is crucial for writing error-free playbooks. By following Ansible’s guidelines and best practices, you can create ‘when’ conditions that are both clear and functional. Properly structured ‘when’ conditions are essential for managing the flow of tasks in your Ansible playbooks, ensuring smooth and reliable automation.

Subscribe to the YouTube channel, Medium, and Website, X (formerly Twitter) to not miss the next episode of the Ansible Pilot.

Academy

Learn the Ansible automation technology with some real-life examples in my Udemy 300+ Lessons Video Course.

BUY the Complete Udemy 300+ Lessons Video Course

My book Ansible By Examples: 200+ Automation Examples For Linux and Windows System Administrator and DevOps

BUY the Complete PDF BOOK to easily Copy and Paste the 250+ Ansible code

Want to keep this project going? Please donate

Patreon Buy me a Pizza