我有两个主持人:
foo
bla
foo
没有host_vars
。 bla
有一个host_vars
个文件,其中包含以下内容:
---
# host_vars/bla
'a': {
'b': {
'c': 'string'
}
}
我的任务只应在复杂JSON存在且包含项b
时运行。我的逻辑是:当a
存在且项目b
时,它还有c
。
我的任务如下:
---
- name: example task
file:
dest: "{{ item.dest }}"
owner: "{{ item.owner }}"
state: directory
with_items:
- { dest: "/tmp/{{ a['b']['c'] }}", owner: root }
when: a['b'] is defined
此任务对bla
成功(因为它具有正确的JSON)但对于错过JSON的foo
失败。
fatal: [foo]: FAILED! => {"failed": true, "msg": "'dict object' has no attribute 'b'"}
ok: [bla] => (item={u'dest': u'/tmp/string', u'owner': u'root'})
skipping: [foo]: => (item={u'dest': u'/tmp/', u'owner': u'root'})
ok: [bla] => (item={u'dest': u'/tmp/string', u'owner': u'root'})
现在我知道为每个项目解释了when语句,因此它不起作用。有人可以提供有效的解决方案吗?
Ansible版本是2.2.0
---
- name: example task
file:
dest: "{{ item.dest }}"
owner: "{{ item.owner }}"
state: directory
with_items:
- { dest: "/tmp/{{ a['b']['c'] | default([]) }}", owner: root }
when: a['b'] is defined
这不起作用,因为在when
之后评估with_items
,只要未定义a['b']
,它就会失败。
fatal: [foo]: FAILED! => {"failed": true, "msg": "'dict object' has no attribute 'b'"}
答案 0 :(得分:0)
- name: example task
file:
dest: "{{ item.dest }}"
owner: "{{ item.owner }}"
state: directory
with_items:
- { dest: "/tmp/{{ (a['b'] | default({}))['c'] | default('nA') }}", owner: root }
when: a['b'] is defined