3

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

2 Answers 2

2

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')]]"
0

Be sure that your task includes the show_tag parameter. I missed it in my first go-around. e.g.

     - name: Gather all registered virtual machines
       community.vmware.vmware_vm_info:
         hostname: '{{ vcenter_hostname }}'
         username: '{{ vcenter_username }}'
         password: '{{ vcenter_password }}'
         show_tag: true
         validate_certs: no
       delegate_to: localhost
       register: vminfo

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .