Interview Prep/Ansible/Jinja2, Conditionals and Loops

How do you control whitespace in Jinja2 templates?

IntermediateConceptJinja2, Conditionals and Loops
Answer

Statement tags leave blank lines and indentation behind. Control it with:

  • {%- ... -%} — a dash trims whitespace on that side
  • trim_blocks (default true in the template module) removes the first newline after a block tag
  • lstrip_blocks: true strips leading spaces before a block tag
- ansible.builtin.template:
    src: haproxy.cfg.j2
    dest: /etc/haproxy/haproxy.cfg
    lstrip_blocks: true

Check output with --diff, and watch for YAML or Python-style files where indentation matters.

All Ansible questions Roadmap: Ansible

More on Jinja2, Conditionals and Loops