只有当变量包含特定字符串运行Ansible任务

问题描述 投票:36回答:7

我有多个任务取决于从变量1的值。我要检查,如果值是{{变量1}},但我得到了一个错误:

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

我使用ansible 2.0.2

linux conditional ansible ansible-playbook ansible-2.x
7个回答
36
投票

如果variable1是一个字符串,而你正在寻找它串,这应该工作:

when: '"value" in variable1'

如果variable1为数组或字典代替,in将搜索完全匹配的字符串作为其项目之一。


36
投票

以上答案都不在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


7
投票

从Ansible 2.5

when: variable1 is search("value")

4
投票

这个例子使用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')

ansible版本:2.4.3.0


4
投票

一些问题的答案不再工作作为解释。

目前,这里是一些在ansible的2.6.x对我的作品

 when: register_var.stdout is search('some_string')

3
投票

用这个

当: “{{在变量1 '值'}}”

代替

当: “在 '值'{{变量1}}”

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

当: “{{变量1 == '值'}}”


-2
投票

我用了

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

意味着 - 失败,只有当先前注册的变量“promtool_version”不包含字符串“1.5.2”。

© www.soinside.com 2019 - 2024. All rights reserved.