ansible regex_search with variable

43,813

Solution 1

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

Solution 2

Wanted to share my complex case with positive look-ahead, positive look-behind and variable in regex_search for those who may need it.

- hosts: localhost
  gather_facts: no
  tasks:
     - set_fact:
          pattern: "{{ 'foobar' | regex_search('foo') }}"
     - set_fact:
          m: "{{ 'beefoo' | regex_search('(?<=prefix-' + pattern | string + '-)' + '([0-9.]+)' + '(?=suffix)') }}"     
     - debug:
          msg: "hi {{ m }}"
Share:
43,813
rok
Author by

rok

Senior infra/software/devops engineer with a strong Python and Java background and a proven track record of delivering high quality solutions. Has particular interest in modern applications architectures which are containerized, orchestrated, highly available, scalable and fault-tolerant. Dives into the guts of a running system to fix issues everyone is happy to pass over. Have experience building PaaS in a private cloud from scratch. Successfully learned any necessary technology at any company and any position to cover the gaps whether it's on site, fully remotely or on customer site. Value provided to companies I worked at always greatly exceeded merely performing my duties.

Updated on July 25, 2022

Comments

  • rok
    rok almost 2 years

    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 }}"
    
  • rok
    rok about 5 years
    thanks, where do i put the bee in '^' + pattern | string?
  • dloeda
    dloeda about 5 years
    Sorry, check it again, bad copy/paste and remember to upvote =)