how do i fetch a specific ip from vmware guestinfo?

IP Address of the first interface can get through the hw_eth0 property of the vmware_guest_info module result.
Here’s the sample playbook.

---
- name: Example Playbook
  hosts: localhost
  gather_facts: false
  vars:
    hostname: test_vm2
  tasks:
    - name: Gather a virtual machine info
      vmware_guest_info:
        hostname: '{{ vsphere_host }}'
        username: '{{ vsphere_user }}'
        password: '{{ vsphere_password }}'
        validate_certs: false
        datacenter: "{{ vsphere_datacenter }}"
        name: "{{ hostname }}"
      register: gather_vm_info

    - name: Display the first interface set IP Address of a virtual machine
      debug:
        msg: >-
          {{ gather_vm_info.instance.hw_eth0.ipaddresses
            | map('ipaddr', 'ipv4')
            | select('!=', false)
            | list
            | first
          }}

The hw_eth0 is the interface information of a virtual machine have.
If you want to get the second interface IP Address, change from hw_eth0 to hw_eth1.
The above playbook uses the ipaddr filter in getting only ipv4 address.
So it needs to install netaddr library.

(venv)$ pip install netaddr

By the way, the following playbook can be possible to get the first interface IP Address too.

---
- name: Example Playbook
  hosts: localhost
  gather_facts: false
    hostname: test_vm2
  tasks:
    - name: Gather a virtual machine info
      vmware_guest_info:
        hostname: '{{ vsphere_host }}'
        username: '{{ vsphere_user }}'
        password: '{{ vsphere_password }}'
        validate_certs: false
        datacenter: "{{ vsphere_datacenter }}"
        name: "{{ hostname }}"
        schema: vsphere
        properties:
          - guest.net
      register: gather_vm_info

    - name: Set device_config_ids variable
      set_fact:
        device_config_ids: >-
         {{ device_config_ids | default([])
           + [item.deviceConfigId]
          }}
      loop: "{{ gather_vm_info.instance.guest.net }}"

    - name: Display the first interface set IP Address of a virtual machine
      debug:
        msg: "{{ item.1.ipAddress.0 }}"
      with_nested:
        - "{{ device_config_ids | sort | first }}"
        - "{{ gather_vm_info.instance.guest.net }}"
      when:
        - item.0 | int == item.1.deviceConfigId

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top