2

I am trying to filter out the list of VMs with specific tags. The sample playbook is as follows :

 - hosts: localhost
   gather_facts: false
   become: false
   vars:
      vcenter_hostname: vcenter3423
      vcenter_username: center\user4325
      vcenter_password: L0gM3In4325
   tasks:
     - name: Gather all registered virtual machines
       community.vmware.vmware_vm_info:
         hostname: '{{ vcenter_hostname }}'
         username: '{{ vcenter_username }}'
         password: '{{ vcenter_password }}'
         validate_certs: no
       delegate_to: localhost
       register: vminfo

     - debug:
         msg: "{{ item.guest_name }}, {{ item.ip_address }}, {{ item.guest_fullname }}, {{ item.datacenter }}, {{ item.power_state }}, {{ item.tags }} "
       with_items:
         - "{{ vminfo.virtual_machines }} | community.general.json_query(query) }}"       
       vars:
         query: "[?guest_name=='CMCUAT']"

However, whatever combination I may try the tags[] output, the rest of the o/p is populated. Not sure what I am missing

1 Answer 1

1

There could be multiple reasons, make sure you have community installed ansible-galaxy collection install community.general also modify debug to use json_query and you should add a separate query for filtering your VMs

here is your file, replace specific_tag in the query with the tag you are looking for

- hosts: localhost
  gather_facts: false
  become: false
  vars:
    vcenter_hostname: vcenter3423
    vcenter_username: center\user4325
    vcenter_password: L0gM3In4325
  tasks:
    - name: Gather all registered virtual machines
      community.vmware.vmware_vm_info:
        hostname: '{{ vcenter_hostname }}'
        username: '{{ vcenter_username }}'
        password: '{{ vcenter_password }}'
        validate_certs: no
      delegate_to: localhost
      register: vminfo

    - debug:
        msg: "{{ item.guest_name }}, {{ item.ip_address }}, {{ item.guest_fullname }}, {{ item.datacenter }}, {{ item.power_state }}, {{ item.tags }} "
      with_items: "{{ vminfo.virtual_machines | community.general.json_query(query) }}"
      vars:
        query: "[?guest_name=='CMCUAT' && tags[?contains(@, 'specific_tag')]]"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.