Listing the names of all virtual machines on an ESXi server
In this particular case the ESXi server was esxihost.
Prerequisites
The following were needed on uvm0:
- Ansible Galaxy collections:
- community.vmware
- Python packages:
- pyVmomi
- requests
The uvm0 host had a Miniconda environment dedicated to Ansible, which contained the two Python packages.
Creating the playbook
Executed:
aadmin@uvm0:~/code/it-wiz/devops/ansible/projects/local/playbooks$ touch list_vm_names.yml
Brought list_vm_names.yml to the following form:
- name: List all virtual machines on ESXi server
hosts: localhost
gather_facts: no
pre_tasks:
- include_vars: vars.yml
tasks:
- name: Get virtual machine information
community.vmware.vmware_vm_info:
hostname: "{{ esxi_server }}"
username: "{{ esxi_username }}"
password: "{{ esxi_password }}"
validate_certs: false
register: vm_info
- name: Display the list of virtual machine names
debug:
msg: "{{ vm_info.virtual_machines | map(attribute='guest_name') | list }}"
when: vm_info.virtual_machines is defined
Execution of the playbook
Executed:
aadmin@uvm0:~/code/it-wiz/devops/ansible/projects/local$ ansible-playbook playbooks/list_vm_names.yml --ask-vault-pass
Details
aadmin@uvm0:~/code/it-wiz/devops/ansible/projects/local$ ansible-playbook playbooks/list_vm_names.yml --ask-vault-pass
Vault password:
PLAY [List all virtual machines on ESXi server] ******************************************************************
TASK [include_vars] **********************************************************************************************
ok: [localhost]
TASK [Get virtual machine information] ***************************************************************************
ok: [localhost]
TASK [Display the list of virtual machine names] *****************************************************************
ok: [localhost] => {
"msg": [
"Arch Linux - arvm00",
"CentOS - pblocal40",
"Ubuntu Server 24 LTS - uvm0",
"Ubuntu Desktop 16 - uvm04",
"Ubuntu Server 14 LTS - uvm05",
"Ubuntu Server 14 LTS - uvm06",
"Ubuntu Server 24 LTS - uvm26",
"Ubuntu Server 24 LTS - uvm27",
"Ubuntu Server 20 LTS - prod0",
"Ubuntu Server 20 LTS - test0",
"Windows 7 Professional - win7vm0",
"Windows 10 Pro - win10vm0",
"Windows 10 Pro - win10vm1"
]
}
PLAY RECAP *******************************************************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0