如何在单块中执行多行 Jinja2 条件?

Mik*_* T. 3 template ansible jinja

以下代码因语法错误而被拒绝:

{%
    if inventory_hostname in groups.aptcache
        set cachehost = 'localhost'
    else
        set cachehost = groups['aptcache'] | first
    endif
%}
cache={{ cachehost }}
Run Code Online (Sandbox Code Playgroud)

我希望,我的意图足够清楚,以便 Jinja2 大师纠正我......拜托?

Mar*_*ner 5

你不能把 if-then-else 放在一个块中,除非它是一个 if 表达式。任何一个:

{% if inventory_hostname in groups.aptcache %}
{%      set cachehost = 'localhost' %}
{% else %}
{%      set cachehost = groups['aptcache'] | first %}
{% endif %}
cache={{ cachehost }}
Run Code Online (Sandbox Code Playgroud)

或者

cache={{ 'localhost' if inventory_hostname in groups.aptcache else groups['aptcache'] | first }}
Run Code Online (Sandbox Code Playgroud)

  • 我知道,我可以 - 但这看起来很丑 - 真的没有办法将它保存在跨越多行的 _single_ {% ... %} 块中吗? (2认同)