ansible regex_search with variable
Asked Answered
W

2

14

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 }}"
Waive answered 7/3, 2019 at 14:46 Comment(0)
T
13

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
Thrawn answered 7/3, 2019 at 15:18 Comment(2)
thanks, where do i put the bee in '^' + pattern | string?Waive
Sorry, check it again, bad copy/paste and remember to upvote =)Thrawn
W
6

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 }}"
Waive answered 7/3, 2019 at 17:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.