Fetch VM Info from Ansible

I’m using the “vmware_vm_info” module to fetch the VM name with the below playbook and it is working fine but if I try to add the ?guest_name==‘vm_name’ as variable it is not working. Can you please suggest how to generalize the play by adding the variable to the guestn_name?

I’m using the “vmware_vm_info” module to fetch the VM name with the below playbook and it is working fine but if I try to add the ?guest_name==‘vm_name’ as variable it is not working. Can you please suggest how to generalize the play by adding the variable to the guestn_name?


  • name: Check if the VM existing the Vcenter
    hosts: localhost
    vars_files: 1credentials.yml
    vars:
    vm_name: server2
    tasks:

  • name: Checking VM details
    block:

  • name: Get virtual machine info
    vmware_vm_info:
    hostname: ‘{{ vcenter_hostname }}’
    username: ‘{{ vcenter_username }}’
    password: ‘{{ vcenter_password }}’
    validate_certs: no
    delegate_to: localhost
    register: vm_info

  • debug:
    msg: “{{ item.guest_name }}”
    with_items:

  • “{{ vm_info.virtual_machines | json_query(query) }}”
    vars:
    query: “[?guest_name==‘server2’]”

Try backticks:

query: “[?guest_name==server2]”

No I mean, it is working if I give ‘server2’ but if I give the variable defined in the vars: section it is not working.

Where are you specifying the vm_name in vmware_vm_info? ansible-doc shows this is a required parameter.

- name: Gather one specific VM
community.vmware.vmware_vm_info:
hostname: ‘{{ vcenter_hostname }}’
username: ‘{{ vcenter_username }}’
password: ‘{{ vcenter_password }}’
vm_name: ‘vm_name_as_per_vcenter’
delegate_to: localhost
register: vm_info

In your example you would need to use “{{ vm_name }}” as the value of the vm_name parameter.

- name: Gather one specific VM
community.vmware.vmware_vm_info:
hostname: ‘{{ vcenter_hostname }}’
username: ‘{{ vcenter_username }}’
password: ‘{{ vcenter_password }}’
vm_name: ‘{{ vm_name }}’
delegate_to: localhost
register: vm_info