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

Ansible Block中字符串比较的OR条件未正常生效问题求助

Ansible When条件使用OR时的逻辑错误解析

这个问题的核心是你在when语句中错误地将布尔表达式包裹成了字符串,导致Ansible的条件判断逻辑失效。

问题原因分析

在你的第二个配置里,每个条件都被双引号完整包裹了:

when: ("'hello-prod.com' in inventory_hostname") or ("'hello-cool-prod.com' in inventory_hostname")

这里的("'hello-prod.com' in inventory_hostname")并不是一个布尔判断,而是一个字符串字面量。在Ansible的布尔评估规则中,任何非空字符串都会被视为True。所以不管你的inventory_hostname是什么,两个非空字符串用or连接的结果永远是True,这就导致Block被错误执行。

而你第一个单条件的写法之所以能正常工作,是因为虽然你加了多余的括号,但没有把整个表达式变成字符串——Ansible会自动解析括号内的布尔逻辑,忽略外层不必要的括号。

正确的写法

你需要去掉每个条件外层的双引号,让它们成为真正的布尔表达式:

- name: Do cool stuff
  block:
    - name: Some tasks
      set_fact: feeder="feeder.stuff.com"
  when: ('hello-prod.com' in inventory_hostname) or ('hello-cool-prod.com' in inventory_hostname)

或者更简洁的方式,直接检查inventory_hostname是否在目标列表中,可读性更好:

- name: Do cool stuff
  block:
    - name: Some tasks
      set_fact: feeder="feeder.stuff.com"
  when: inventory_hostname in ['hello-prod.com', 'hello-cool-prod.com']

这样Ansible就能正确评估条件:只有当inventory_hostname匹配列表中的任意一个值时,才会执行Block,否则就会跳过,完全符合你的预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 17:02:46