Search code examples
ansiblejinja2

Insert carriage returns in Jinja template rendered with Ansible


I am writing an Ansible template for a CSV file with very long lines:

{{ hostvars[h]['myvar'][0]['firstvar'] | default('foo') }},{{ hostvars[h]['myvar'][0]['secondvar'] | default('bar') }},{{ hostvars[h]['myvar'][0]['thirdvar'] | default('baz') }}, {# ... #} 

I'd like to split the lines for readability (after the ,), but this also insert carriage returns into the template output, breaking it.
How can carriage returns be inserted in the line without appearing in the output?


Solution

  • You can use Jinja's whitespace control for this use case:

    {{ hostvars[h]['myvar'][0]['firstvar'] | default('foo') }},
    {{- hostvars[h]['myvar'][0]['secondvar'] | default('bar') }},
    {{- hostvars[h]['myvar'][0]['thirdvar'] | default('baz') }}
    

    Or you can use the fact that a block can be wrapped on multiple lines without causing any blanks:

    {{ 
      hostvars[h]['myvar'][0]['firstvar'] | default('foo') 
    }},{{ 
      hostvars[h]['myvar'][0]['secondvar'] | default('bar') 
    }},{{ 
      hostvars[h]['myvar'][0]['thirdvar'] | default('baz') 
    }}
    

    Side note: using the dot notation, when accessing attributes of a dictionary could also lighten a bit the syntax:

    {{ hostvars[h]['myvar'][0]['firstvar'] | default('foo') }}
    

    could also be written

    {{ hostvars[h].myvar.0.firstvar | default('foo') }}