首页 > 解决方案 > 即使满足条件,Ansible“何时”条件也不起作用

问题描述

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

...
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 包含逗号 (,) 或连字符 (-) 并且 variable2 等于“trunk”,那就是真的!当它为真时,条件满足并且它应该失败,但是,整个工作成功完成。我在这里缺少什么?先感谢您。

标签: ansibleansible-2.x

解决方案


TL;博士

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

(注意:在子句中列出条件用when连接它们and

解释

variable1.find('-')正在返回字符串XX字符的整数索引,或者-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只是更精确(以防函数有一天会返回一些其他负值......),我也猜想放弃这个特定搜索的比较是一个错字你上面的代码。

尽管如此,这是 IMO 编写此类测试的一种糟糕方式,我更喜欢为此使用可用的 ansible 测试

$ 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接受 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 中的示例作为最终结果。


推荐阅读