如何定义复杂JSON中的项目时如何运行Ansible任务?

时间:2016-12-22 21:14:28

标签: json ansible ansible-2.x

我有两个主持人:

  • foo
  • bla

foo没有host_varsbla有一个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'"}

1 个答案:

答案 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