Skip to content

Jinja create file from template without empty lines

Issue

Creation of file from pillar simple list with Jinja template will be create empty line, in top or bottom of file, dependence for template syntax. You can not create file without empty lines.

#!/usr/bin/python
from jinja2 import Template

d = {'testlist':['item1','item2','item3']}

tmpl = '''{%- for item in testlist %}
   {{ item }}
{%- endfor %}'''

t = Template(tmpl)
print( t.render( d ) )

Result:

                <<< empty line
   item1
   item2
   item3

Solution

Convert pillars to plain text, and use "contents" parameter for "file.managed".

{%- set dict = SOME_PILLAR_ITEM_TYPE_DICT %}
{%- set output=[] %}
{%- for i_name,i_value in dict.items() %}
{%- do output.append("%s=%s" % (i_name,i_value)) %}
{%- endfor %}

save_{{ file }}:
  file.managed:
    - name: {{ file }}
    - contents: {{ output|sort(attribute='0') }}