PromQL使用!~正则不匹配报错,Prometheus配置加载失败如何解决?
问题:Prometheus告警规则解析错误(忽略WireGuard设备时)
问题描述
为了在网络错误告警中忽略WireGuard设备,编写了如下Prometheus告警规则:
- alert: HostNetworkReceiveErrors expr: 'rate(node_network_receive_errs_total[2m]) / rate(node_network_receive_packets_total[2m]) > 0.01 and device !~ "\.*wg\\d+"' for: 2m labels: severity: warning annotations: summary: Host Network Receive Errors (instance {{ $labels.instance }}:{{ $labels.device }}) description: Instance interface has encountered {{ printf "%.0f" $value }} receive errors in the last five minutes.\n VALUE = {{ $value }}
加载配置时出现错误:
could not parse expression: 1:108: parse error: unexpected character after '!': '~'
问题原因
核心问题是YAML字符串的转义处理有误,导致Prometheus无法正确识别!~操作符:
- 在YAML单引号包裹的字符串中,内部混用双引号时,反斜杠的转义逻辑会出现异常,破坏了PromQL表达式的语法结构;
- 原正则表达式中的
\.*是错误写法——你想匹配任意前缀应该用.*,而\.*实际匹配的是任意数量的点字符; - 双重转义的
\\d在YAML解析后,传递给PromQL的内容不符合正则语法要求。
解决方法
调整告警规则的expr字段,修正YAML转义和正则表达式:
方案1:用单引号包裹正则表达式(YAML中转义单引号)
- alert: HostNetworkReceiveErrors expr: 'rate(node_network_receive_errs_total[2m]) / rate(node_network_receive_packets_total[2m]) > 0.01 and device !~ ''^.*wg\d+$''' for: 2m labels: severity: warning annotations: summary: Host Network Receive Errors (instance {{ $labels.instance }}:{{ $labels.device }}) description: Instance interface has encountered {{ printf "%.0f" $value }} receive errors in the last five minutes.\n VALUE = {{ $value }}
- YAML单引号字符串内部的单引号需要写成两个
''完成转义; - 正则
^.*wg\d+$匹配任意前缀+wg+数字结尾的设备(比如wg0、eth1.wg1),若只需匹配纯wg开头的设备(如wg0),可改为^wg\d+$。
方案2:用双引号包裹整个expr字段(转义内部双引号和反斜杠)
- alert: HostNetworkReceiveErrors expr: "rate(node_network_receive_errs_total[2m]) / rate(node_network_receive_packets_total[2m]) > 0.01 and device !~ \".*wg\\d+\"" for: 2m labels: severity: warning annotations: summary: Host Network Receive Errors (instance {{ $labels.instance }}:{{ $labels.device }}) description: Instance interface has encountered {{ printf "%.0f" $value }} receive errors in the last five minutes.\n VALUE = {{ $value }}
- YAML双引号字符串中,
\\会被转义为\,\"会被转义为",最终传递给PromQL的正则表达式为.*wg\d+,符合语法要求。
内容的提问来源于stack exchange,提问作者Derkades
相关产品推荐
相关产品推荐

