How to do multiline Jinja2 conditionals in single block?

14,038

You can't put the if-then-else in one block unless it is an if-expression. Either:

{% if inventory_hostname in groups.aptcache %}
{%      set cachehost = 'localhost' %}
{% else %}
{%      set cachehost = groups['aptcache'] | first %}
{% endif %}
cache={{ cachehost }}

or

cache={{ 'localhost' if inventory_hostname in groups.aptcache else groups['aptcache'] | first }}
Share:
14,038

Related videos on Youtube

Mikhail T.
Author by

Mikhail T.

Updated on September 18, 2022

Comments

  • Mikhail T.
    Mikhail T. over 1 year

    The below code is rejected as syntactically incorrect:

    {%
        if inventory_hostname in groups.aptcache
            set cachehost = 'localhost'
        else
            set cachehost = groups['aptcache'] | first
        endif
    %}
    cache={{ cachehost }}
    

    I hope, my intent is clear enough for a Jinja2 guru to correct me... Please?

  • Mikhail T.
    Mikhail T. over 6 years
    I know, I can -- but that seems ugly -- is there really no way to keep it in a single {% ... %} block spanning multiple lines?