1

稳定:2.9

你应该什么时候在 Ansible中使用!=or is notin whenbefore ?include: create_dir.yml

示例代码:

- name: "Get stat"  
   stat:
     path: "/tmp"
   register: stat_result

- include: create_dir.yml
  when: stat_result.exists is not True
4

1 回答 1

1

首先,您在此处生成的任务中确实存在两个问题:

  1. 您想使用模块file或模块stat,但不是两者的奇怪混合
  2. stat模块会给你一个stat包含密钥的复杂类型exists,所以你真的应该测试stat_result.stat.exists

所以,下面的解释是基于任务的:

- stat:
    path: "/tmp"
  register: stat_result

- include: create_dir.yml
  when: stat_result.stat.exists is not true

几个工作任务。


正如 Jinja 的文档中所指出的:

is:执行测试

来源https://jinja.palletsprojects.com/en/2.11.x/templates/#other-operators

!=:比较两个对象的不等式。

来源https://jinja.palletsprojects.com/en/2.11.x/templates/#comparisons

但由于在 Jinja 中定义了 atrue()false()测试,你确实可以编写如下内容:

when: stat_result.stat.exists is not true()

所以一个较短的版本将是

when: stat_result.stat.exists is not true 
# because the test function receives no parameters

现在确实这个测试类似于

when: stat_result.stat.exists != True

除了is not true测试更健壮并且可以更好地处理未定义的变量!= True

例如,如果您确实评论了您的stat任务,则测试

when: stat_result.stat.exists is not true

会成功,而

when: stat_result.stat.exists != True

会引发致命错误:

条件检查 'stat_result.stat.exists != True' 失败。错误是:评估条件时出错(stat_result.stat.exists!= True):'stat_result'未定义


现在这个测试真的不是最优的,因为你不应该做你应该做的事情when: bool_var is not truewhen: not bool_var所以:

when: not stat_result.stat.exists
于 2021-04-08T19:41:50.443 回答