我在 ansible playbook 中使用 regex_findall 从字符串中提取 ipv4 地址时遇到问题。这是 ansible 有问题的行似乎是:
- 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
Run Code Online (Sandbox Code Playgroud)
问题可能出在哪里?
如果您给出一个可重现的示例,将会很有帮助。这是一个:
- 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."
Run Code Online (Sandbox Code Playgroud)
使用-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') }}"
Run Code Online (Sandbox Code Playgroud)
所以我的第一个猜测似乎已经修复了它 - 双反斜杠反斜杠。
- 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."
Run Code Online (Sandbox Code Playgroud)