我有多个任务取决于变量 1 的值。我想检查值是否在 {{variable1}} 中,但出现错误:
- name: do something when the value in variable1
command: <command>
when: "'value' in {{variable1}}"
我正在使用 ansible 2.0.2
我有多个任务取决于变量 1 的值。我想检查值是否在 {{variable1}} 中,但出现错误:
- name: do something when the value in variable1
command: <command>
when: "'value' in {{variable1}}"
我正在使用 ansible 2.0.2
如果variable1
是一个字符串,并且您正在其中搜索一个子字符串,这应该可以工作:
when: '"value" in variable1'
ifvariable1
是一个数组或字典,in
将搜索确切的字符串作为其项目之一。
在 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]"
从 Ansible 2.5
when: variable1 is search("value")
一些答案不再像解释的那样起作用。
目前这里是在 ansible 2.6.x 中对我有用的东西
when: register_var.stdout is search('some_string')
此示例使用 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
这在 Ansible 2.9 中对我有用:
variable1 = www.example.com.
variable2 = www.example.org.
when: ".com" in variable1
而不是:
when: not ".com" in variable2
用这个
何时:“{{'value' in variable1}}”
代替
何时:“{{variable1}} 中的‘值’”
同样对于字符串比较,您可以使用
何时:“{{ variable1 == 'value' }}”
在 Ansible 2.9.2 版中:
如果您的变量 variable1 被声明:
when: "'value' in variable1"
如果您注册了 variable1,则:
when: "'value' in variable1.stdout"
我用了
failed_when: not(promtool_version.stdout.find('1.5.2') != -1)
意味着 - 仅当先前注册的变量“promtool_version”不包含字符串“1.5.2”时才会失败。