跳到内容

no-changed-when

此规则检查任务是否将更改返回到结果或条件。除非任务仅读取信息,否则应确保它们通过以下方式返回更改

  • 注册结果或条件,并使用 changed_when 子句。
  • 使用 createsremoves 参数。

您应该始终在不能自然检测到是否发生更改的任务上使用 changed_when 子句。最常见的示例包括运行任意命令的 shellcommand 模块。

一种非常常见的解决方法是使用布尔值,例如如果任务从不更改任何内容则使用 changed_when: false ,或者如果它始终更改某些内容则使用 changed_when: true,但是您也可以使用任何表达式,包括使用任务的已注册结果的表达式,就像我们在下面的示例中一样。

此规则也适用于处理程序,而不仅适用于任务,因为它们也是任务。

有问题的代码

---
- name: Example playbook
  hosts: localhost
  tasks:
    - name: Does not handle any output or return codes
      ansible.builtin.command: cat {{ my_file | quote }} # <- Does not handle the command output.

正确的代码

---
- name: Example playbook
  hosts: localhost
  tasks:
    - name: Handle shell output with return code
      ansible.builtin.command: cat {{ my_file | quote }}
      register: my_output # <- Registers the command output.
      changed_when: my_output.rc != 0 # <- Uses the return code to define when the task has changed.