81

我有多个任务取决于变量 1 的值。我想检查值是否在 {{variable1}} 中,但出现错误:

- name: do something when the value in variable1
  command: <command>
  when: "'value' in {{variable1}}"

我正在使用 ansible 2.0.2

4

9 回答 9

89

如果variable1是一个字符串,并且您正在其中搜索一个子字符串,这应该可以工作:

when: '"value" in variable1'

ifvariable1是一个数组或字典,in将搜索确切的字符串作为其项目之一。

于 2016-04-08T10:35:36.830 回答
47

在 ansible 2.3.0.0 中,以上答案都不适用于我,但以下答案:

when: variable1 | search("value")

在 ansible 2.9 中,不赞成使用 ~ 连接进行变量替换:

when: "variable1.find('v=' ~ value) == -1"

http://jinja.pocoo.org/docs/dev/templates/#other-operators

其他选项:

when: "inventory_hostname in groups[sync_source]"
于 2017-05-25T17:55:58.760 回答
29

从 Ansible 2.5

when: variable1 is search("value")
于 2018-08-31T09:31:35.747 回答
14

一些答案不再像解释的那样起作用。

目前这里是在 ansible 2.6.x 中对我有用的东西

 when: register_var.stdout is search('some_string')
于 2019-02-11T19:10:19.790 回答
7

此示例使用 regex_search 执行子字符串搜索。

- name: make conditional variable
  command: "file -s /dev/xvdf"
  register: fsm_out

- name: makefs
  command: touch "/tmp/condition_satisfied"
  when: fsm_out.stdout | regex_search(' data')

版本:2.4.3.0

于 2018-04-30T13:28:09.787 回答
6

这在 Ansible 2.9 中对我有用:

variable1 = www.example.com. 
variable2 = www.example.org. 

when: ".com" in variable1

而不是:

when: not ".com" in variable2
于 2020-05-12T17:32:23.337 回答
6

用这个

何时:“{{'value' in variable1}}”

代替

何时:“{{variable1}} 中的‘值’”

同样对于字符串比较,您可以使用

何时:“{{ variable1 == 'value' }}”

于 2018-09-13T17:50:11.813 回答
5

在 Ansible 2.9.2 版中:

如果您的变量 variable1 被声明:

when: "'value' in variable1"

如果您注册了 variable1,则:

when: "'value' in variable1.stdout"

于 2020-03-04T01:04:53.927 回答
-2

我用了

failed_when: not(promtool_version.stdout.find('1.5.2') != -1)

意味着 - 仅当先前注册的变量“promtool_version”不包含字符串“1.5.2”时才会失败。

于 2017-03-30T13:10:57.440 回答