Search code examples
ansiblevmware

Ansible - vmware: how to find a guest on a multiple hosts vcenter?


One of the many Ansible Community.VMWare modules parameters is 'hostname', which is the name of the ESXi server.

In my case, a guest could be in one of multiple ESXi servers (8, for now), and also a new server could be added by the support team at any time.

Is there a way to find on which ESXi server a guest is? Or is it mandatory that I know this at start?

I could have a list of the ESXi servers, keep updating it on demand, and loop over this list using module 'community.vmware.vmware_guest_find' and "with_items", but actually, I don't know how would I do this (iterate over the servers, changing the 'hostname', and stopping when I finally find the guest).

Any help?


Solution

  • I came up with this solution below. It's necessary to have previously the list of ESXi hosts.

    [...]
    vars:
      vcenters_hostname:
        - vcenter01
        - vcenter02
        - ...
    [...]
    - block:
        - name: Navigate throughout all vcenters looking for the guest
          community.vmware.vmware_guest_find:
            hostname: "{{ item }}"
            username: "{{ vcenter_username }}"
            password: "{{ vcenter_password }}"
            name: "{{ guest_name }}"
            validate_certs: no
          delegate_to: localhost
          register: guest_find_result
          with_items: "{{ vcenter_hostnames }}"
      rescue:
        - name: Doing nothing only to don't raise a fail message
          meta: noop
      always:
        - name: Record which vcenter and folder is the guest
          ansible.builtin.set_fact:
            guest_folder: "{{ item['folders'][0] }}"
            vcenter_hostname: "{{ item['item'] }}"
          with_items: "{{ guest_find_result['results'] }}"
          when: item['failed'] == false