Ansible – playing with Jinja2 and its whitespace control

Ansible – playing with Jinja2 and its whitespace control

4 October 2018 3 By Eric Deleforterie

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

 

 

 

 

 

Please follow and like us: