2
votes

I try to get a specific value from dict var with Ansible but my code doesn't works fine.

Below my code:

- 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 }}"

Below dict structure:

{
"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
}}

Error message returned by 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" }

1
print vm_list with debug and you'll see that it is not a dict, so you need to run your loop accordingly.Konstantin Suvorov
Can you decide whether it's a list or a dictionary? You even call it a list.techraf
@KonstantinSuvorov below my vm_list contentgfunk
Registered variable on a loop-task is always a dict which has a results list inside which contains lots of keys about each item execution. Please inspect it with debug module.Konstantin Suvorov

1 Answers

0
votes

Thanks for your return, now it works fine.

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