即使满足条件,Ansible "when" 条件也不起作用

Ansible "when" condition is not functioning even if the condition is met

我不明白为什么我的条件不起作用,也许这里有人可以帮助我。我的剧本中有以下内容:

...
tasks:
- fail: msg="This and that, you can't run this job"
  when: (variable1.find(',') != -1 or variable1.find('-')) and (variable2.find("trunk") != -1 )

我认为这应该这样解释:如果 variable1 包含逗号 (,) 或连字符 (-) AND variable2 等于“trunk”,那么它是正确的!当它为真时,条件满足并且它应该失败,但相反,整个工作成功完成。我在这里缺少什么?提前谢谢你。

TL;DR

tasks:
  - fail:
      msg: "This and that, you can't run this job"
    when:
      - variable1 is search('[,-]+')
      - variable2 is search("trunk")

(注意:when 子句中的列表条件用 and 连接它们)

说明

variable1.find('-') 是 returning X 其中 X 是字符串中字符的整数索引,如果不存在则为 -1不是布尔值。

$ ansible localhost -m debug -a msg="{{ variable1.find('-') }}" -e variable1="some-val"
localhost | SUCCESS => {
    "msg": "4"
}

请注意,字符串第一个字母上的连字符将导致索引 0

您将 X 直接作为布尔值求值,这是一种不好的做法。无论如何,即使你将它正确地评估为一个布尔值,结果仍然是:

$ ansible localhost -m debug -a msg="{{ variable1.find('-') | bool }}" -e variable1="no hyphen"
localhost | SUCCESS => {
    "msg": false
}
$ ansible localhost -m debug -a msg="{{ variable1.find('-') | bool }}" -e variable1="hyphen- <= here"
localhost | SUCCESS => {
    "msg": false
}

除非连字符在索引 1 上的非常特殊的情况下(在这种情况下继续努力寻找错误....)

$ ansible localhost -m debug -a msg="{{ variable1.find('-') | bool }}" -e variable1="a-val with hyphen at index 1"
localhost | SUCCESS => {
    "msg": true
}

了解以上内容后,您对连字符是否存在的实际测试应该是:

$ ansible localhost -m debug -a msg="{{ variable1.find('-') >= 0 }}" -e variable1="-hyphen at start"
localhost | SUCCESS => {
    "msg": true
}
$ ansible localhost -m debug -a msg="{{ variable1.find('-') >= 0 }}" -e variable1="hyphen- <= here"
localhost | SUCCESS => {
    "msg": true
}
$ ansible localhost -m debug -a msg="{{ variable1.find('-') >= 0 }}" -e variable1="no hyphen"
localhost | SUCCESS => {
    "msg": false
}

这与您的其他比较(即 != -1)或多或少相同,除了更精确(以防有一天该函数会 return 其他负值...)和我还猜想放弃这个特定搜索的比较是你上面代码中的错字。

尽管如此,在我看来,这是一种编写此类测试的糟糕方法,我更愿意为此使用 available ansible tests

$ ansible localhost -m debug -a msg="{{ variable1 is search('-') }}" -e variable1="no hyphen"
localhost | SUCCESS => {
    "msg": false
}
$ ansible localhost -m debug -a msg="{{ variable1 is search('-') }}" -e variable1="-hyphen at start"
localhost | SUCCESS => {
    "msg": true
}
$ ansible localhost -m debug -a msg="{{ variable1 is search('-') }}" -e variable1="hyphen- <= here"
localhost | SUCCESS => {
    "msg": true
}

search accepts regexps 开始,您甚至可以一次查找多个必填字符:

$ ansible localhost -m debug -a msg="{{ variable1 is search('[,-]+') }}" -e variable1="a,value"
localhost | SUCCESS => {
    "msg": true
}
$ ansible localhost -m debug -a msg="{{ variable1 is search('[,-]+') }}" -e variable1="some-value"
localhost | SUCCESS => {
    "msg": true
}
$ ansible localhost -m debug -a msg="{{ variable1 is search('[,-]+') }}" -e variable1="some value"
localhost | SUCCESS => {
    "msg": false
}

上面我的 TL;DR 中的示例给出了最终结果。