ansible regex_search with variable

rok picture rok · Mar 7, 2019 · Viewed 31.1k times · Source

How to find a match using regex in ansible playbook where variable appears in the regex_search argument?

The following playbook doesn't find the match... when run using: ansible-playbook playbook.yml

- hosts: localhost
  gather_facts: no
  tasks:
     - set_fact:
          pattern: "{{ 'foobar' | regex_search('foo') }}"
     - set_fact:
          m: "{{ 'beefoo' | regex_search('bee{{ pattern }}') }}"     
     - debug:
          msg: "hi {{ m }}"

Answer

dloeda picture dloeda · Mar 7, 2019

Depends on the ansible's version you're using. As far as I know, you can use that expression in a version greater than 2.4.0. For lower versions you can use regex_search('^' + pattern | string).

So your code will be something like this:

- hosts: localhost
  gather_facts: no
  tasks:
     - set_fact:
          pattern: "{{ 'foobar' | regex_search('foo') }}"
     - set_fact:
          m: "{{ 'beefoo' | regex_search('bee' + pattern | string) }}"     
     - debug:
          msg: 'hi ' + m | string