ansibleansible-2.x

Matching multiple strings in regex_search or regex_findall gives other strings which should not match


Although I have checked previous similar questions, none seems to apply/work for me. We're on Ansible version 2.9 as long as the rest of our infra will not be updated. I have this list underneath which I need to filter on two strings.

kvm_list:
  - abcdefabcfgh.domain.example
  - deffghabc.domain.example
  - abcblabla.domain.example
  - kabcxyz.domain.example
  - kesanu.domain.example
  - kesbapo.domain.example
  - kextoet.domain.example
  - kptfkom.domain.example
  - kgitblabla.domain.example
  - kgitblubblub.domain.example
- name: "get them devtools"
  hosts: localhost
  ignore_errors: True
  tasks: 
    - set_fact:
         devtools: "{{ kvm_list | string | regex_search('kgit.*|kes.*', multiline=True)}}"
    
    - debug: var=devtools

When trying the above I get the underneath:

TASK [debug] **************************************************************************************************************************
ok: [localhost] => {
"msg":"kesanu.domain.example','kesbapo.domain.example','kextoet.domain.example','kptfkom.domain.example','kgitblabla.domain.example','kgitblubblub.domain.example]"
}

Kextoet and kptfkom should not be included.

When testing this purely on regex ( https://regex101.com/ ) it works, when testing this in ansible it does not.

When using regex_findall, I get the same result.

When doing a regex search on one string it is correct.

If anybody could throw some hints or point to the obvious, I would be most grateful.


Solution

  • The select filter can achieve that:

    - set_fact:
        devtools: "{{ kvm_list | select('match','k(?:git|es)') }}"
    
    ok: [localhost] => {
        "devtools": [
            "kesanu.domain.example",
            "kesbapo.domain.example",
            "kgitblabla.domain.example",
            "kgitblubblub.domain.example"
        ]
    }