
如何将 and 和 eq/ne 函数组合在一起?
我写了这个片段
{{ define "opsgenie.default.tmpl" }}
{{.commonlabels.alertname }}
{{- range $i, $alert := .alerts }}
{{ .annotations.description }}
{{- end -}}
{{- "\n" -}}
{{- "\n" -}}
{{- if and eq .commonlabels.infoalert "true" eq .commonlabels.topic "database" -}}
grafana: https://{{ .commonlabels.url }}
{{- "\n" -}}{{- end -}}
{{- if and ne .commonlabels.infoalert "true" eq .commonlabels.topic "database" -}}
database:
• https://{{ .commonlabels.url }}/
• https://{{ .commonlabels.url }}/
{{- "\n" -}}{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
目标是:
- 如果我的警报包含两个标签
infoalert: true和topic:database则仅显示 grafana 链接 - 如果我的警报仅包含标签
topic: database但不包含infoalert: true则仅显示 databsse 链接
它看起来像条件 {{- if and eq .commonlabels.infoalert "true" eq .commonlabels.topic "database" -}} 的语法不正确,因为我在警报时在alertmanager.log中收到此错误被解雇:
培训招生教育类网站模板(响应式)安装即用,自带人人站CMS内核,支持响应式,前端banner轮播图文本均已进行可视化配置,伪静态页面生成,支持内容模型、多语言、自定义表单、筛选、多条件搜索等功能,支持多种URL模式及模型。模板特点:1、安装即用,自带人人站CMS内核及企业站展示功能(产品,新闻,案例展示等),并可根据需要增加表单 搜索等功能(自带模板) 2、支持响应式 3、前端banner轮播图文
notify retry canceled due to unrecoverable error after 1 attempts: templating error: template: email.tmpl:24:17: executing \"opsgenie.default.tmpl\" at: wrong number of args for eq: want at least 1 got 0
正确答案
只需使用括号对表达式进行分组:
{{- if and (eq .commonlabels.infoalert "true") (eq .commonlabels.topic "database") -}}
{{- if and (ne .commonlabels.infoalert "true") (eq .commonlabels.topic "database") -}}
查看这个可测试的示例:
func main() {
t := template.must(template.new("").parse(src))
m := map[string]any{
"infoalert": "true",
"topic": "database",
}
if err := t.execute(os.stdout, m); err != nil {
panic(err)
}
fmt.println("second round")
m["infoalert"] = "false"
if err := t.execute(os.stdout, m); err != nil {
panic(err)
}
}
const src = `
{{- if and (eq .infoalert "true") (eq .topic "database") -}}
infoalert is true and topic is database
{{- end -}}
{{- if and (ne .infoalert "true") (eq .topic "database") -}}
infoalert is not true and topic is database
{{ end }}
`
这将输出(在 go playground 上尝试):
infoalert is true and topic is database Second round infoalert is NOT true and topic is database









