Go Template中and与eq/ne函数组合语法错误,求正确实现方式
解决Alertmanager Go Template条件语法错误及逻辑实现
问题背景
需要实现以下告警链接展示逻辑:
- 当告警同时包含
infoalert: true和topic: database标签时,仅展示Grafana链接 - 当告警仅包含
topic: database标签但infoalert不为true时,仅展示Database链接
之前的模板代码因eq函数参数缺失触发Alertmanager报错:
notify retry canceled due to unrecoverable error after 1 attempts: templating error: template: email.tmpl:24:17: executing "opsgenie.default.tmpl" at <eq>: wrong number of args for eq: want at least 1 got 0
正确的模板写法
基础版本(假设infoalert标签始终存在)
{{ if and (eq .Labels.infoalert "true") (eq .Labels.topic "database") }} Grafana链接:[查看Grafana](https://your-grafana-url) {{ else if and (eq .Labels.topic "database") (ne .Labels.infoalert "true") }} Database链接:[查看Database](https://your-db-url) {{ end }}
健壮版本(兼容infoalert标签不存在的情况)
如果告警可能没有infoalert标签,需要先判断标签是否存在,避免空引用错误:
{{ if and (hasKey .Labels "infoalert") (eq .Labels.infoalert "true") (eq .Labels.topic "database") }} Grafana链接:[查看Grafana](https://your-grafana-url) {{ else if and (eq .Labels.topic "database") (or (not (hasKey .Labels "infoalert")) (ne .Labels.infoalert "true")) }} Database链接:[查看Database](https://your-db-url) {{ end }}
关键语法说明
eq/ne函数必须传入至少两个参数,不能出现无参数的调用,这是之前报错的核心原因and函数的每个条件都需要用括号包裹,确保每个条件都是独立完整的布尔表达式hasKey函数用于判断标签是否存在,避免标签缺失时访问.Labels.infoalert引发的错误
内容的提问来源于stack exchange,提问作者olti
相关产品推荐
相关产品推荐

