'How to pass a variable using match filter in ansible [closed]

I am trying to list VMs from the vcenter, filtering VM names which starts with linTest and winTest. How can I pass linTest|winTest as a variable in the code below?

  - name: Gather all registered virtual machines
    vmware_vm_info:
      hostname: '{{ vc_host }}'
      username: '{{ vc_user }}'
      password: '{{ vc_pass }}'
      validate_certs: False
    delegate_to: localhost
    register: vminfo

  - set_fact:
      vm_hostname: "{{ vminfo.virtual_machines | map(attribute='guest_name')|select('match', '^(linTest|winTest)')| list }} "

  - debug:
      var: vm_hostname 


Solution 1:[1]

I understand that you like to pass a variable regluar expression to the filter. To do so you could use an approach like

...
vars:

  REGEX: '^(linTest|winTest)'

tasks:

- set_fact:
      vm_hostname: "{{ vminfo.virtual_machines | map(attribute='guest_name') | select('match', REGEX) | list }}"
...

in short select('match', REGEX).

Further Q&A

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1