跳转到内容

no-handler

此规则检查对结果或条件更改的正确处理。

如果一个任务有 when: result.changed 条件,它实际上充当一个 handler。 推荐的方法是使用 notify 并将任务移动到 handlers。 如果需要,可以通过在行尾添加 # noqa: no-handler 注释来静默此规则。

问题代码

---
- name: Example of no-handler rule
  hosts: localhost
  tasks:
    - name: Register result of a task
      ansible.builtin.copy:
        dest: "/tmp/placeholder"
        content: "Ansible made this!"
        mode: 0600
      register: result # <-- Registers the result of the task.
    - name: Second command to run
      ansible.builtin.debug:
        msg: The placeholder file was modified!
      when: result.changed # <-- Triggers the no-handler rule.
---
# Optionally silences the rule.
when: result.changed # noqa: no-handler

正确代码

以下代码包含与问题代码相同的功能,而无需记录 result 变量。

---
- name: Example of no-handler rule
  hosts: localhost
  tasks:
    - name: Register result of a task
      ansible.builtin.copy:
        dest: "/tmp/placeholder"
        content: "Ansible made this!"
        mode: 0600
      notify:
        - Second command to run # <-- Handler runs only when the file changes.
  handlers:
    - name: Second command to run
      ansible.builtin.debug:
        msg: The placeholder file was modified!