有没有办法检查 ansible 任务中未定义字典键?

Lui*_*dez 31 conditional ansible ansible-playbook

所以在我的代码中我有一个任务

- name: cool task
  shell: 'touch iamnotcool.txt'
  when: me.cool is not defined
Run Code Online (Sandbox Code Playgroud)

我的 vars 看起来像

---
me:
  stumped: yes
Run Code Online (Sandbox Code Playgroud)

因此,当我运行任务时,它会返回以下错误

{"failed": true, "msg": "The conditional check 'me.cool' failed. The error was: error while evaluating conditional (me.cool): 'dict object' has no attribute 'cool'.
Run Code Online (Sandbox Code Playgroud)

tec*_*raf 41

您包含的语法:

when: me.cool is not defined
Run Code Online (Sandbox Code Playgroud)

是正确的。

您还可以使用not in

when: "'cool' not in me"
Run Code Online (Sandbox Code Playgroud)

问题是您的错误消息:

条件检查“me.cool”失败。

声称您的病情定义为:

when: me.cool
Run Code Online (Sandbox Code Playgroud)

因此,要么您使用的版本中存在一些错误(但您没有分享它是哪一个)并且存在已知问题,要么您没有发布导致错误的确切任务。

  • 如果他没有发布原始代码并省略了第二个引用相同值的 when-condition,则错误仍然可能发生。这有效: `when: is_installed.rc is defined and is_installed.rc == 0` 这不是: `when: is_installed.rc is defined` `\n` `when is_installed.rc == 0` (2认同)

小智 12

您可以通过使用 jinja2 selectattr() 语法来避免“dict object”没有属性,如下所示:

when: me|selectattr("cool", "defined")|list|length >0
Run Code Online (Sandbox Code Playgroud)

从 Michael Hoglan 获得的想法https://groups.google.com/forum/#!topic/ansible-project/8XJkHQgttLA