jsjw
jsjw

Reputation: 317

Ansible vmware_host_fact with a loop

I'm trying to get a list of all of the datastores across multiple ESXi hosts (they all sit in different vCenters so I'm having to use a loop with a dictionary to get the correct vCenter for the ESXi host otherwise the hosts do not appear)

My problem is trying to comprehend the output. I've read the docs and I can't seem to figure a clear way to get the output I want. Consider the following from the docs as a working example - on one ESXi host.

- name: Gather vmware host facts from vCenter
  vmware_host_facts:
    hostname: "{{ vcenter_server }}"
    username: "{{ vcenter_user }}"
    password: "{{ vcenter_pass }}"
    esxi_hostname: "{{ esxi_hostname }}"
  register: host_facts
  delegate_to: localhost
- debug:
    var: host_facts['ansible_facts']['ansible_datastore']

In my example, I add a loop to this to get the correct combination:

- name: Gather vmware host facts from vCenter
  vmware_host_facts:
    hostname: "{{ item.vcs }}"
    username: "{{ vcenter_user }}"
    password: "{{ vcenter_pass }}"
    esxi_hostname: "{{ item.host }}"
  register: host_facts
  delegate_to: localhost
  loop:
     - { host: 'mtboskt1bl07.oam.eeint.co.uk', vcs: 'vmtvcsakt01.oam.eeint.co.uk' }
     - { host: 'mtaoskt1bl10.oam.eeint.co.uk', vcs: 'vmtvcsakt01.oam.eeint.co.uk' }

The var 'host_facts' is a dictionary containing three entries: msg, changed and result.

If I access result - it is a list of dictionaries but I cannot seem to access any entries.

I've looked at the 'subelement' documentation but can't see how I'd apply it here. Anyone able to assist me further?

Edit: Below is how I achieved this:

- debug:
      msg: "{{ item['ansible_facts']['ansible_datastore'] }}"
    loop: "{{ host_facts['results'] }}"

Upvotes: 0

Views: 384

Answers (1)

Zeitounator
Zeitounator

Reputation: 44615

Simply get the exact same variable in each item looping over the results from the previous loop:

- debug:
    var: item.ansible_facts.ansible_datastore
  with_items: "{{ host_facts.results }}"

Upvotes: 1

Related Questions