Jinja spacing error
Nothing can be more frustrating as receiving a jinja spacing error while linting your code. . You know that there is nothing wrong with it, it runs without any errors and still every time you run the linter, this error pops up: Improve jinja spacing....
The code:
- name: Add the controller to the names of the templates
ansible.builtin.set_fact:
ee_on_templates: >-
[
{%- for i in range(_template_list | length) -%}
'{{ inventory_hostname }} {{ i }}'
{%- if not loop.last -%},
{%- endif -%}
{%- endfor -%}
]
In the above code, we did everything to remove spaces... like {%- -%} and still the linter complains.
It looks like valid code, and it is... But:
WARNING Listing 1 violation(s) that are fatal
jinja[spacing]: Jinja2 spacing could be improved: [ {%- for i in range(_template_list | length) -%} '{{ inventory_hostname }} {{ i }}' {%- if not loop.last -%}, {%- endif -%} {%- endfor -%} ] -> [{%- for i in range(_template_list | length) -%} '{{ inventory_hostname }} {{ i }}'{%- if not loop.last -%},{%- endif -%} {%- endfor -%} ] (warning)
check_data.yml:84 Jinja2 template rewrite recommendation: `[{%- for i in range(_template_list | length) -%} '{{ inventory_hostname }} {{ i }}'{%- if not loop.last -%},{%- endif -%} {%- endfor -%} ]`.
The final trick is not to try to ignore the error, but change the set_fact ever so slightly:
- name: Add the controller to the names of the templates
ansible.builtin.set_fact:
ee_on_templates: >-
[
{%- for i in range(_template_list | length) -%}
'{{ inventory_hostname }} {{ i }}'
{%- if not loop.last -%},
{%- endif -%}
{%- endfor -%}
]
The | instead of > makes all the difference..