ansible regex_search 与变量

rok*_*rok 8 regex ansible ansible-template

如何在变量出现在regex_search参数中的 ansible playbook 中使用正则表达式找到匹配项?

以下剧本找不到匹配项...运行时使用: 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 }}"
Run Code Online (Sandbox Code Playgroud)

dlo*_*eda 10

取决于ansible您使用的's 版本。据我所知,您可以在 2.4.0 以上的版本中使用该表达式。对于较低版本,您可以使用regex_search('^' + pattern | string).

所以你的代码将是这样的:

- 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
Run Code Online (Sandbox Code Playgroud)


rok*_*rok 6

regex_search我想与那些可能需要它的人分享我的复杂案例,其中包括积极的前瞻、积极的后瞻和可变。

- 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 }}"
Run Code Online (Sandbox Code Playgroud)