即使满足该条件,Ansible的“ when”条件也不起作用

问题描述

我不明白为什么我的病情不起作用,也许有人可以帮我解决这个问题。我的剧本中包含以下内容

...
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”,那么它是正确的!如果为true,则满足该条件,并且该条件应该失败,但是,整个工作已成功完成。我在这里想念的是什么?预先谢谢你。

解决方法

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('-')返回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)大致相同,只是更为精确(以防函数有一天会返回其他负值...),我也想删除比较对于此特定搜索,就是您上面的代码中的错字。

尽管如此,这是IMO编写此类测试的一种较差的方式,我更愿意为此使用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中的示例。