Introduction

Ansible, the popular open-source automation platform, provides a powerful and flexible way to automate tasks, manage configurations, and orchestrate processes. However, to ensure the maintainability and readability of Ansible playbooks, it's important to adhere to best practices and guidelines. In this article, we'll explore Ansible Error 206, "jinja[spacing]", in [Ansible-Lint](/articles/ansible-lint) which is related to Jinja2 string templates. We'll discuss how this rule helps improve readability and reduce the likelihood of typos by enforcing proper spacing in Jinja2 templates within your Ansible playbooks.

The Problem: Jinja Spacing

Ansible Error 206, "jinja[spacing]", checks for the correct spacing within Jinja2 string templates. Specifically, it ensures there are spaces between variables and operators, including filters, such as {{ var_name | filter }}. Proper spacing not only enhances readability but also makes it less likely for typographical errors to occur.

Problematic Code Example:

``yaml

---

  • name: Example error 206

hosts: all

tasks:

- name: Error 206

ansible.builtin.debug:

vars:

foo: "{{some|dict2items}}" # <-- jinja[spacing]

when: "{{ foo | bool }}" # <-- jinja[spacing] - 'when' has implicit templating

`

In the problematic code above, Jinja2 templates need to have the appropriate spacing between variables, operators, and filters, making the code less readable and prone to typos.

Output:

`bash

WARNING Listing 3 violation(s) that are fatal

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

206.yml:5 Task/Handler: Error 206

no-jinja-when: No Jinja2 in when.

206.yml:5 Task/Handler: Error 206

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

206.yml:8 Jinja2 template rewrite recommendation: {{ some | dict2items }}.

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

Rule Violation Summary

count tag profile rule associated tags

2 jinja[spacing] basic formatting (warning)

1 no-jinja-when basic deprecations

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

`

Correcting Jinja Spacing

Use the appropriate spacing to address Ansible Error 206 and ensure that your Jinja2 templates are correctly formatted for readability and accuracy. Here's the corrected code:

`yaml

---

  • name: Example error 206

hosts: all

tasks:

- name: Error 206

ansible.builtin.debug:

vars:

foo: "{{ some | dict2items }}"

when: foo | bool

`

In the corrected code, spaces have been added between variables, operators, and filters, improving readability and reducing the likelihood of typos.

Implicit Templating in Ansible

It's important to note that in Ansible, some fields like changed_when, failed_when, unt