检查模式下的 Ansible 未定义变量

Ansible undefined variables in check mode

考虑这个剧本:

---
- name: test
  hosts: localhost
  gather_facts: no
  tasks:

  - name: foo
    shell: echo foo                             # skipped when running in check mode
    register: result

  - debug: msg="foo"
    when: (result is defined)
          and (result.stdout == 'foo')

我认为 is defined 会像其他语言一样导致短路评估,但事实并非如此。

如果这是 运行 检查模式,我得到:

fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout'

我知道我可以忽略 ignore_errors: "{{ansible_check_mode}}" 的错误,但我想了解如何解决这个问题。

如何重写 when 子句以防止引用未定义的变量?

实际上,如果你在没有条件的情况下调试 var,你会看到它已被定义。它根本不包含 stdout 键,因为任务已被跳过。解决此问题的正确方法(非详尽列表):

- debug: msg="{{ result.stdout | default('no value') }}
  when: result.stdout | default('') == 'foo'
- debug: msg="foo"
  when:
    - result is not skipped
    - result.stdout == 'foo'

请注意,由于您上面的 shell 示例没有更改远程目标上的任何内容,您也可以决定在 运行 处于检查模式时播放它:

  - name: foo
    shell: echo foo
    check_mode: false
    changed_when: false
    register: result

  - debug: msg="foo"
    when: result.stdout == 'foo'