Search code examples
ansibleansible-inventoryansible-facts

How to use ipaddresses variable from vsphere_guest results in playbook?


I want use the variable ipaddresses of vsphere_guest. I want to use the name of the virtual machine in vSphere first to get its IP address and then to run Ansible plays on that machine using the IP address.

So far I have:

- hosts: localhost
  gather_facts: false

  vars_prompt:
    - name: "inventory_hostname"
      prompt: "Enter virtual machine name"
      private: no
      default: "ansible-test"


  vars:
    vcenter_hostname: '192.168.250.1'
    vcenter_user: 'root'
    vcenter_pass: 'pass'

  tasks:
    - vsphere_guest:
        vcenter_hostname: "{{ vcenter_hostname }}"
        username: "{{ vcenter_user }}"
        password: "{{ vcenter_pass }}"
        guest: "{{ inventory_hostname }}"
        vmware_guest_facts: yes
        validate_certs: no
      register: vsphere_facts

How should I proceed?


Solution

  • Assuming you want to run another play on the virtual machine for which you obtained ipaddresses variable (and has one IP address or it's reachable using the first IP address on the list), you can continue your playbook:

    - hosts: localhost
      gather_facts: false
    
      vars_prompt:
        - name: "inventory_hostname"
          prompt: "Enter virtual machine name"
          private: no
          default: "ansible-test"
    
      vars:
        vcenter_hostname: '192.168.250.1'
        vcenter_user: 'root'
        vcenter_pass: 'pass'
    
      tasks:
        - vsphere_guest:
            vcenter_hostname: "{{ vcenter_hostname }}"
            username: "{{ vcenter_user }}"
            password: "{{ vcenter_pass }}"
            guest: "{{ inventory_hostname }}"
            vmware_guest_facts: yes
            validate_certs: no
          register: vsphere_facts
    
        - name: Ensure virtual machine is in the dynamic inventory
          add_host:
            name: "{{ vsphere_facts.ansible_facts.hw_eth0.ipaddresses[0] }}"
            ansible_user: _______
            ansible_ssh_private_key_file: _______
            groups: virtual_machines
    
    - name: A play to be run on the virtual machine
      hosts: virtual_machines
      tasks:
        - debug: