带有变量的正则表达式

问题描述:

如何在正弦剧本中使用正则表达式查找匹配项,其中变量出现在 regex_search 参数中?

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

使用以下代码运行时,以下剧本找不到匹配的内容...: ansible-playbook playbook.yml

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 }}"

取决于您使用的 ansible 的版本.据我所知,您可以在高于2.4.0的版本中使用该表达式.对于较低版本,可以使用 regex_search('^'+模式|字符串).

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