使用 ansible 语法解析 json

使用 ansible 语法解析 json

以下是登记册的内容:

- debug:
    var: vmfacts.virtual_machines


ok: [localhost] => {
"vmfacts.virtual_machines": {
    "2k12r2-k11": {
        "guest_fullname": "Microsoft Windows Server 2012 (64-bit)", 
        "ip_address": "10.0.1.20", 
        "mac_address": [
            "00:50:56:00:00:20"
        ], 
        "power_state": "poweredOn", 
        "uuid": "421d5210-8a64-2d60-8b44-02de952600d1"
    }, 

下面工作正常,但我需要上面的 uuid 值

- shell: "echo {{ item }}"
  with_items: "{{ vmfacts.virtual_machines }}"

似乎无法解码语法,这些似乎都不起作用:

“回显 {{ item.uuid }}” “回显 {{ item.0.uuid }}” “回显 {{ item[0].uuid }}”

访问 uuid 值的正确方法是什么?

答案1

vmfacts.virtual_machinesdict

with_items当应用于dict仅对其键进行迭代时。

因此,要么:

- shell: "echo {{ vmfacts.virtual_machines[item].uuid }}"
  with_items: "{{ vmfacts.virtual_machines }}"

或者更好的用法with_dict

- shell: "echo {{ item.value.uuid }}"
  with_dict: "{{ vmfacts.virtual_machines }}"

相关内容