Timofey Pasichnik
Timofey Pasichnik

Reputation: 23

Ansible newline in jinja template

I am trying to create docker-compose config with Ansible. I am using Jinja2 template for this.

Here is part of jinja template code:

    image: {% if version == "4.2" %}appname:4.2.0{% elif version == "4.0.5" %}dockerhub2:10000/appname:4.0.5{% else %}dockerhub2:10000/appname3:3.0.14{%  endif %}
    container_name: {{ dir }}

What I expect to see:

    image: dockerhub2:10000/appname3:3.0.14
    container_name: name

What I really see:

    image: dockerhub2:10000/appname3:3.0.14    container_name: name

How can I describe a newline here?

Upvotes: 1

Views: 2004

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68034

Put endif on the next line. Quoting from Whitespace Control

"a single trailing newline is stripped if present"

    image: {% if version == "4.2" %}appname:4.2.0{% elif version == "4.0.5" %}dockerhub2:10000/appname:4.0.5{% else %}dockerhub2:10000/appname3:3.0.14
{%  endif %}
    container_name: {{ dir }}

FWIW, you can simplify the template (and make the case easily extendible too)

    image: {{ image[ver] }}
    container_name: {{ dir }}

if you put the data into the dictionary

    image:
      '4.2': 'appname:4.2.0'
      '4.0.5': 'dockerhub2:10000/appname:4.0.5'
      default: 'dockerhub2:10000/appname3:3.0.14'
    ver: "{{ (version in image.keys())|ternary(version, 'default') }}"

Credit @mdaniel; the template below gives the same result

    image: {{ image.get(version, image.get('default')) }}
    container_name: {{ dir }}

Upvotes: 4

Related Questions