如何在Ansible playbook中正确使用regex_findall?

时间:2018-01-30 01:25:38

标签: regex ansible

我在ansible playbook中使用regex_findall来从字符串中提取ipv4地址时遇到问题。这是安全的违规行似乎是:

- debug:
    msg: "{{ item.stdout | regex_findall('\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b') }}"
                                                         ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes.  Always quote template expression brackets when they
start a value. For instance:

with_items:
  - {{ foo }}

Should be written as:

with_items:
  - "{{ foo }}"

exception type: <class 'yaml.scanner.ScannerError'>
exception: while parsing a quoted scalar
in "<unicode string>", line 29, column 14
found unknown escape character
in "<unicode string>", line 29, column 62
output

问题出在哪里?

1 个答案:

答案 0 :(得分:2)

如果您提供可重复的示例,这会很有帮助。这是一个:

- hosts: localhost
  connection: local
  vars:
    xyz: "hello"
  tasks:
  - debug:
      msg: "{{ xyz | regex_findall('\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b') }}"
  - debug: msg="done."

使用-vvv,我会收到更具描述性的错误消息:

exception type: <class 'yaml.scanner.ScannerError'>
exception: while scanning a double-quoted scalar
  in "<unicode string>", line 7, column 12:
          msg: "{{ xyz | regex_findall('\b(?:[0 ...
               ^
found unknown escape character '.'
  in "<unicode string>", line 7, column 53:
     ...  regex_findall('\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b') }}"

所以我的第一个猜测似乎已经修复了它 - 反斜杠的双反斜杠。

- hosts: localhost
  connection: local
  vars:
    # xyz: "hello"
    xyz: "1.2.3.4"
  tasks:
  - debug:
      msg: "{{ xyz | regex_findall('\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b') }}"
  - debug: msg="done."