【问题标题】:Ansible regular expression to match a string and extract the lineAnsible 正则表达式匹配字符串并提取行
【发布时间】:2019-07-03 20:58:09
【问题描述】:

我试图在一行中的 1 个空格之后找到一个字符串,如果它存在,则提取完整的行并存储在不同的变量中。我正在使用 ansible 和正则表达式。如果字符串存在于任何其他位置,则不应匹配。

我尝试使用 regex_match 并选择但出现错误。

  vars:
    input : "{{ lookup('template', '{{ file }}') }}"
    target: "{{ input | regex_search('^(?=.*\b INPUT\b)(?:\S+){1}(\S*.*)')}}"

错误总是出现在同一位置“(?:\S+)”。

ERROR! Syntax Error while loading YAML.
  found unknown escape character 'S'

The offending line appears to be:

    input : "{{ lookup('template', '{{ file }}') }}"
    target: "{{ input | regex_search('^(?=.*\b INPUT\b)(?:\S+){1}(\S*.*)')}}"

^ here
    input : "{{ lookup('template', '{{ file }}') }}"
    target: "{{ input | select('match', '^(?=.*\b INPUT\b)(?:\S+){1}(\S*.*)' | list | first}}"

^ here

我还尝试为 / 包含转义字符,但也出现错误。

ERROR! Syntax Error while loading YAML.
  found unknown escape character 'S'

The offending line appears to be:

   input : "{{ lookup('template', '{{ file }}') }}"
    target: "{{ input | regex_search('^(?=.*/\b INPUT/\b)(?:/\S){1}(/\S*.*)')}}"
                                                                                ^ here

我的变量文件

-P INPUT ACCEPT
-A INPUT -s 1.1.1.1/32 -j ACCEPT
-A INPUT -s 2.2.2.2/32 -j ACCEPT
-A INPUT -s 3.3.3.3/32 -j ACCEPT
-A INPUT -j RH-Firewall
-N RH-Firewall
-A RH-Firewall -j INPUT
-A RH-Firewall -p icmp -m icmp --icmp-type 0 -j ACCEPT
-A RH-Firewall -p icmp -m icmp --icmp-type 3 -j ACCEPT
-A RH-Firewall-1 -p icmp -m icmp --icmp-type 11 -j ACCEPT
-A RH-Firewall -p icmp -m icmp --icmp-type 11 -j ACCEPT

target_rule_set 应该只包含前 5 行。同样,如果我匹配 RH-Firewall,那么它应该包含第 6-11 行。

【问题讨论】:

    标签: regex ansible


    【解决方案1】:

    您可以将regex_findallmultiline=True 一起使用:

    (?m)^\S+\s+INPUT\b.*
    

    请参阅regex demo。详情:

    • ^ - 使用 (?m) 开始一行
    • \S+ - 1+ 非空白字符
    • \s+ - 1+ 个空格
    • INPUT\b - INPUT 整体而言
    • .* - 该行的其余部分。

    在代码中:

    target: "{{ input | regex_findall('^\\S+\\s+INPUT\\b.*', multiline=True)}}"
    

    【讨论】:

    • 感谢维克托。正则表达式有效,但 (?m) 没有迭代变量。它在第一次出现搜索字符串后停止。
    • @Knightfox 这不是(?m) 的责任。将re.search 替换为re.findall
    • regex_findall 仍然没有搜索多行。从 ansible docs 发现我们需要添加 multiline=True。 target: "{{ input | regex_findall('^\\S+\\s+INPUT\\b.*', multiline=True) }}"
    • @Knightfox 太好了,调整了答案。
    猜你喜欢
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 2013-12-25
    • 1970-01-01
    相关资源
    最近更新 更多