Parsing dictionary from VMware module

Viewed 17

I'm using ansible community.vmware.vmware_datacenter_info.I only want to get the name of my several datacenter in vCenter.

Here is my play:

 ---
 - hosts: localhost
   gather_facts: False

   tasks:
   - name: Gather information about all datacenters
     community.vmware.vmware_datacenter_info:
       hostname: "{{ vCenter }}"
       username: "{{ vCenter_username }}"
       password: "{{ vCenter_password }}"
       validate_certs: False
     delegate_to: localhost
     register: result

Here is the output of my variable result:

TASK [Print the gateway for each host when defined] ********************************
ok: [localhost] => {
    "msg": {
        "changed": false,
        "datacenter_info": [
            {
                "config_status": "gray",
                "moid": "datacenter-271",
                "name": "Sample_DC_1",
                "overall_status": "gray"
            },
            {
                "config_status": "gray",
                "moid": "datacenter-276",
                "name": "Sample_DC_2",
                "overall_status": "gray"
            }
        ],
        "failed": false
    }
}

What I would like to get is only the name for both datacenter: Sample_DC_1 and Simple_DC_2 so I can use them in another play.

What I tried:

  - name: Display datacenter name
     debug:
       msg:
         - "{{ item.value.name }}"
     loop: "{{ lookup('dict', result)  }}"

Result:

fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'bool object' has no attribute 'name

if I only try to display "Key: {{ item.key }}" & " Value: {{ item.value }}" I got this output:

"msg": [
        "Key : datacenter_info Value : [{'name': 'Sample_DC_1', 'moid': 'datacenter-271', 'config_status': 'gray', 'overall_status': 'gray'}, {'name': 'Sample_DC_2', 'moid': 'datacenter-276', 'config_status': 'gray', 'overall_status': 'gray'}]"
    ]

How can I register my both datacenter's name in a var so I can re-use them later in the playbook?

1 Answers

Q: "Get the names of both datacenter."

A: Map the attribute

dc_names: "{{ result.datacenter_info|map(attribute='name')|list }}"

Example of a complete playbook for testing

- hosts: localhost

  vars:
    result:
      changed: false
      datacenter_info:
      - config_status: gray
        moid: datacenter-271
        name: Sample_DC_1
        overall_status: gray
      - config_status: gray
        moid: datacenter-276
        name: Sample_DC_2
        overall_status: gray
      failed: false
    dc_names: "{{ result.datacenter_info|map(attribute='name')|list }}"

  tasks:
    - debug:
        var: dc_names

gives

  dc_names:
  - Sample_DC_1
  - Sample_DC_2
Related