Introduction

Ansible is a powerful tool for automating IT tasks, including configuration management, application deployment, and task automation. When writing Ansible playbooks, it's essential to be aware of various rules and best practices to ensure your automation runs smoothly and avoids common errors. One such rule is no-jinja-when, which checks conditional statements for Jinja expressions in curly brackets {{ }}.

The Role of Conditional Statements in Ansible

Conditional statements are vital in Ansible playbooks. They allow you to define when a particular task should run based on certain conditions. Ansible processes conditional statements primarily in the context of the when, failed_when, and changed_when clauses. These statements help determine whether a task should be executed or not.

The no-jinja-when Rule

The no-jinja-when rule aims to ensure that conditional statements are correctly structured. It advises against using Jinja expressions in curly brackets {{ }} within when clauses. Instead, the rule recommends using facts or variables directly in these statements.

Problematic Code

``yaml

---

  • name: Example playbook

hosts: localhost

tasks:

- name: Shut down Debian systems

ansible.builtin.command: /sbin/shutdown -t now

when: "{{ ansible_facts['os_family'] == 'Debian' }}" # <- Nests a Jinja expression in a conditional statement.

`

In the problematic code above, a Jinja expression is enclosed in curly brackets within the when clause. While it may seem like a valid approach, it's not in line with Ansible best practices.

Ansible Lint Output

`bash

WARNING Listing 3 violation(s) that are fatal

jinja[spacing]: Jinja2 spacing could be improved: {{ ansible_facts['os_family'] == 'Debian' }} -> ansible_facts['os_family'] == 'Debian' (warning)

no-jinja-when.yml:5 Task/Handler: Shut down Debian systems

no-changed-when: Commands should not change things if nothing needs doing.

no-jinja-when.yml:5 Task/Handler: Shut down Debian systems

no-jinja-when: No Jinja2 in when.

no-jinja-when.yml:5 Task/Handler: Shut down Debian systems

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

1 no-changed-when shared command-shell, idempotency

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

`

Correct Code

`yaml

---

  • name: Example playbook

hosts: localhost

tasks:

- name: Shut down Debian systems

ansible.builtin.command: /sbin/shutdown -t now

when: ansible_facts['os_family'] == "Debian" # <- Uses facts in a conditional statement.

`

The correct code adheres to the no-jinja-when rule by using facts directly in the when` clause. This ensur