即使满足该条件,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,则满足该条件,并且该条件应该失败,但是,整个工作已成功完成。我在这里想念的是什么?先感谢您。

Zeitounator

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写这种测试的一种糟糕方法,我更愿意为此使用可用的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中的示例。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章