Interview Prep/Ansible/YAML, Syntax and Jinja2 Errors

The rendered Nginx config has random blank lines and broken indentation

BeginnerTroubleshootingYAML, Syntax and Jinja2 Errors
Answer

Likely causes → Jinja keeps the newline after each {% %} tag and the spaces in front of it. With the template module's defaults (trim_blocks: true, lstrip_blocks: false), indented block tags still leave stray whitespace behind.

Fix →

- ansible.builtin.template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    lstrip_blocks: true

Or use whitespace control in the template: {%- for s in servers %} / {% endfor -%}.

Prevent → Add #jinja2: lstrip_blocks: True as the first line of complex templates, and review the --diff output in pull requests.

All Ansible questions Roadmap: Ansible

More on YAML, Syntax and Jinja2 Errors