在vars/main.yml
中我有这个:
user_data:
service:
name: hello1
description: abc
update:
name: hello
version: 1
在剧本中我尝试编写条件:
- name: "stop all"
systemd:
name: "does not matter.service"
state: stopped
when: user_data.service.update is defined
它有效。
当我在条件下使用 update
编写此任务时:
- name: "stop all"
systemd:
name: "does not matter.service"
state: stopped
when: user_data.service.update.name is defined
已跳过
所有变量都在 vars/main.yml
中设置或使用额外的 var 作为 JSON 进行传递。
出了什么问题?
最佳答案
update
实际上是一个保留字(即 dict 对象的内置方法)。请参阅以下剧本。您可以在 yaml 中定义 update
哈希键,但我没有找到任何方法来正确检索它。我目前看到的唯一解决方案(除了在 github ansible 项目上触发票证之外)是将您的哈希 key 重命名为其他名称。
以下剧本
---
- name: Debug that tricky thing
hosts: localhost
gather_facts: false
vars:
user_data:
service:
name: hello1
description: abc
update:
name: hello
version: 1
tasks:
- name: Show the full var
debug:
var: user_data
- name: Try to how the update hash test1
debug:
var: user_data.update
- name: Try to how the update hash test2
debug:
var: user_data["update"]
结果
PLAY [Debug that tricky thing] ******************************************************************************************************************************************************************************************************************************************
TASK [Show the full var] ************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"user_data": {
"service": {
"description": "abc",
"name": "hello1",
"update": {
"name": "hello",
"version": 1
}
}
}
}
TASK [Try to how the update hash test1] ***************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"user_data.update": "<built-in method update of dict object at 0x7fc5d9256630>"
}
TASK [Try to how the update hash test2] ***********************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"user_data[\"update\"]": "<built-in method update of dict object at 0x7fc5d9256630>"
}
PLAY RECAP **************************************************************************************************************************************************************************************************************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
关于python - 比较两个变量时的 Ansible,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59627842/