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 }}
Related videos on Youtube
Author by
Mikhail T.
Updated on September 18, 2022Comments
-
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. over 6 yearsI know, I can -- but that seems ugly -- is there really no way to keep it in a single {% ... %} block spanning multiple lines?