如何使用 Ansible 从字典中检索特定值

How to retrieve specific value from dict with Ansible

我尝试使用 Ansible 从 dict var 中获取特定值,但我的代码无法正常工作。

在我的代码下面:

- name: "Creating VMs for [{{env}}] environment"
  vmware_guest:
    hostname: "{{item.value.vcenter_hostname}}"
    username: "{{item.value.vsphere_username}}"
    password: "{{item.value.vsphere_password}}"
    esxi_hostname: "{{item.value.esxi_hostname}}"
    datacenter: "{{item.value.esxi_datacenter}}"
    folder: "{{item.value.vm_folder}}"
    name: "{{item.key}}"
    state: poweredon
    hardware:
      memory_mb: "{{item.value.vm_memory}}"
      num_cpus: "{{item.value.vm_cpu}}"
    nic:
    - vlan: "{{item.value.vm_networks_vlan}}"
      device_type: "{{item.value.vm_networks_device_type}}"
    template: "{{item.value.vm_template}}"
    wait_for_ip_address: yes
  register: vm_list
  with_dict: "{{vsphere_provisioning}}"

- name: "Print IP"
  debug:
    msg: "Ip Address: {{ item.value.instance.ipv4 }}"
  with_dict: "{{ vm_list }}"

字典结构以下:

{
"changed": true, 
"failed": false, 
"instance": {
    "hw_eth13": {
        "addresstype": "assigned", 
        "ipaddresses": [
            "x.x.x.x", 
            "x::x:x:x:x"
        ], 
        "label": "Network adapter 1", 
        "macaddress": "x:x:x:x:x:x", 
        "macaddress_dash": "x-x-x-x-x-x", 
        "summary": "DVSwitch: x x x x x x x x-x x X x x x x x"
    }, 
    "hw_guest_full_name": "CentOS 4/5/6/7 (64-bit)", 
    "hw_guest_id": "centos64Guest", 
    "hw_interfaces": [
        "ethx"
    ], 
    "hw_memtotal_mb": 2048, 
    "hw_name": "XX_XX_XX", 
    "hw_power_status": "poweredOn", 
    "hw_processor_count": 1, 
    "hw_product_uuid": "xxx-xxx-xxx-xxx-xxx", 
    "ipv4": "XXX.XXX.XXX.XXX", 
    "ipv6": "XXX.XXX.XXX.XXX", 
    "module_hw": true
}}

Ansible返回的错误信息:

fatal: [localhost]: FAILED! => { "failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'ansible.vars.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'instance' The error appears to have been in '/.../tasks/main.yml': line 30, column 3, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be:- name: "Print IP Address" here" }

感谢您的return,现在可以正常使用了。

- name: "Print IP Address"
  debug:
    msg: "IP Address: {{ item.instance.ipv4 }}"
  with_items: "{{ vm_list.results }}"