如何在剧本中使用 vsphere_guest 结果中的 ipaddresses 变量?

How to use ipaddresses variable from vsphere_guest results in playbook?

我想使用 vsphere_guest 的变量 ipaddresses。我想先在 vSphere 中使用虚拟机的名称来获取其 IP 地址,然后 运行 Ansible 使用 IP 地址在该机器上播放。

到目前为止我有:

- 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

我应该如何进行?

假设您想 运行 在您获得 ipaddresses 变量的虚拟机上再玩一次(并且有一个 IP 地址或者可以使用列表中的第一个 IP 地址访问),您可以继续你的剧本:

- 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: