Search code examples
ansibleansible-filter

How to pass a variable using match filter in ansible


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

  • 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