You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jinja2模板主机名匹配判断逻辑失效问题求助

Fixing Jinja2 Condition Always Applying Development Config for All Hosts

我刚接触Jinja2时也踩过这个逻辑运算符优先级的坑!你的问题出在条件表达式的写法上,让我给你拆解一下:

你的原代码:

{% if 'dev' or 'tst' or 'test' or 'eng' in ansible_hostname %} {{ developmenthosts }} {% else %} {{ productionhosts }} {% endif %}

Jinja2会把这个条件解析成:('dev') or ('tst') or ('test') or ('eng' in ansible_hostname)。而非空字符串在布尔判断里会被视为True,所以前面的'dev'已经让整个条件成立了,完全不会往后判断'eng' in ansible_hostname这部分——这就是为什么所有主机都应用了developmenthosts配置。

下面给你几种正确的写法:

写法1:逐个判断每个字符串是否在主机名中

这种方式最直观,适合字符串数量不多的场景:

{% if 'dev' in ansible_hostname 
   or 'tst' in ansible_hostname 
   or 'test' in ansible_hostname 
   or 'eng' in ansible_hostname %}
    {{ developmenthosts }}
{% else %}
    {{ productionhosts }}
{% endif %}

写法2:使用any()函数简化判断

如果后续要添加更多标识字符串,用列表配合any()会更简洁易维护:

{% set dev_env_identifiers = ['dev', 'tst', 'test', 'eng'] %}
{% if any(identifier in ansible_hostname for identifier in dev_env_identifiers) %}
    {{ developmenthosts }}
{% else %}
    {{ productionhosts }}
{% endif %}

写法3:使用正则匹配(适合更复杂的匹配规则)

如果需要更灵活的匹配(比如区分大小写或者特定位置的字符串),可以用Jinja2的search测试器:

{% if ansible_hostname is search('dev|tst|test|eng') %}
    {{ developmenthosts }}
{% else %}
    {{ productionhosts }}
{% endif %}

这几种写法都会正确判断主机名中是否包含指定的任意一个字符串,只有符合条件的主机才会应用developmenthosts配置,其他主机则使用productionhosts。

内容的提问来源于stack exchange,提问作者d1530

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 14:32:26