Vmware 标签和 Ansible,在 Ansible 中为空,但虚拟机有标签

Vmware 标签和 Ansible,在 Ansible 中为空,但虚拟机有标签

我正在尝试过滤具有特定标签的虚拟机列表。示例剧本如下:

 - 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[] 输出的哪种组合,其余的 o/p 都会被填充。不知道我遗漏了什么

答案1

原因可能有多种,请确保您已安装社区ansible-galaxy collection install community.general并进行修改debug以供使用json_query ,并且您应该添加单独的查询来过滤您的虚拟机

这是您的文件,specific_tag在查询中用您要查找的标签替换

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

答案2

确保你的任务包括show_tag范围。我第一次尝试时就错过了。例如

     - 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

相关内容