Ansible – playing with Jinja2 and its whitespace control
Jinja2 templating with Ansible is powerfull and sometimes you could have some headache for positionning the result just where you want to respect a configuration file syntax.
Following, I will show you how to manage the whitespace control with Jinja2
Without specifying whitespace control
{ "Clusters":{ "properties": { {% if Var is defined %} "myParameter": "value1", {% else %} "myParameter": "value2", {% endif %} } } }
Result :
{ "Clusters":{ "properties": { "myParameter": "value2", } } }
As you can see the spaces of each lines will be keeped causing a gap
With – everywhere
{ "Clusters":{ "properties": { {%- if Var is defined -%} "myParameter": "value1", {%- else -%} "myParameter": "value2", {%- endif -%} } } }
Result :
{ "Clusters":{ "properties": {"myParameter": "value2",} } }
As you can see it will removed all the spaces and newlines
With a – in front
{ "Clusters":{ "properties": { {%- if Var is defined %} "myParameter": "value1", {% else %} "myParameter": "value2", {% endif %} } } }
Result :
{ "Clusters":{ "properties": { "myParameter": "value2", } } }
As you can see, the newline before the {%-
will be removed and the spaces in front of the line are concatenate at the end of the previous line
With a – at the end of each block
{ "Clusters":{ "properties": { {% if Var is defined -%} "myParameter": "value1", {% else -%} "myParameter": "value2", {% endif -%} } } }
Result :
{ "Clusters":{ "properties": { "myParameter": "value2", } } }
As you can see this will removed all the spaces and newlines from the removed lines
With a – at the beginning of each block
{ "Clusters":{ "properties": { {%- if Var is defined %} "myParameter": "value1", {%- else %} "myParameter": "value2", {%- endif %} } } }
Result :
{ "Clusters":{ "properties": { "myParameter": "value2", } } }
As you can see the all the newlines will be removed and the spaces keeped
merci! ça m’a servi
Ah ah ah, moi aussi pas plus tard qu’il y a 2 semaines avec une topology Knox récalcitrante
saved my butt. this was killing me!