将警报管理器配置为以 JSON 格式向 Amazon SNS 发送消息 - Amazon Managed Service for Prometheus

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

将警报管理器配置为以 JSON 格式向 Amazon SNS 发送消息

默认情况下,Amazon Managed Service for Prometheus 警报管理器以纯文本列表格式输出消息。这可能会增加其他服务的解析难度。您可以将警报管理器配置为以 JSON 格式发送警报。JSON 可以简化 Amazon SNS 在 AWS Lambda 或 Webhook 接收端点中的下游消息处理。您可以定义一个自定义模板来以 JSON 格式输出消息内容,这样可以更轻松地在下游函数中进行解析,而不必使用默认模板。

要以 JSON 格式将警报管理器中的消息输出到 Amazon SNS,请更新警报管理器配置,在 template_files 根部分中包含以下代码:

default_template: | {{ define "sns.default.message" }}{{ "{" }}"receiver": "{{ .Receiver }}","status": "{{ .Status }}","alerts": [{{ range $alertIndex, $alerts := .Alerts }}{{ if $alertIndex }}, {{ end }}{{ "{" }}"status": "{{ $alerts.Status }}"{{ if gt (len $alerts.Labels.SortedPairs) 0 -}},"labels": {{ "{" }}{{ range $index, $label := $alerts.Labels.SortedPairs }}{{ if $index }}, {{ end }}"{{ $label.Name }}": "{{ $label.Value }}"{{ end }}{{ "}" }}{{- end }}{{ if gt (len $alerts.Annotations.SortedPairs ) 0 -}},"annotations": {{ "{" }}{{ range $index, $annotations := $alerts.Annotations.SortedPairs }}{{ if $index }}, {{ end }}"{{ $annotations.Name }}": "{{ $annotations.Value }}"{{ end }}{{ "}" }}{{- end }},"startsAt": "{{ $alerts.StartsAt }}","endsAt": "{{ $alerts.EndsAt }}","generatorURL": "{{ $alerts.GeneratorURL }}","fingerprint": "{{ $alerts.Fingerprint }}"{{ "}" }}{{ end }}]{{ if gt (len .GroupLabels) 0 -}},"groupLabels": {{ "{" }}{{ range $index, $groupLabels := .GroupLabels.SortedPairs }}{{ if $index }}, {{ end }}"{{ $groupLabels.Name }}": "{{ $groupLabels.Value }}"{{ end }}{{ "}" }}{{- end }}{{ if gt (len .CommonLabels) 0 -}},"commonLabels": {{ "{" }}{{ range $index, $commonLabels := .CommonLabels.SortedPairs }}{{ if $index }}, {{ end }}"{{ $commonLabels.Name }}": "{{ $commonLabels.Value }}"{{ end }}{{ "}" }}{{- end }}{{ if gt (len .CommonAnnotations) 0 -}},"commonAnnotations": {{ "{" }}{{ range $index, $commonAnnotations := .CommonAnnotations.SortedPairs }}{{ if $index }}, {{ end }}"{{ $commonAnnotations.Name }}": "{{ $commonAnnotations.Value }}"{{ end }}{{ "}" }}{{- end }}{{ "}" }}{{ end }} {{ define "sns.default.subject" }}[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}]{{ end }}
注意

此模板根据字母数字数据创建 JSON。如果您的数据包含特殊字符,请在使用此模板之前对其进行编码。

为确保在传出通知中使用此模板,请在您的 alertmanager_config 数据块中引用该模板,如下所示:

alertmanager_config: | global: templates: - 'default_template'
注意

此模板适用于整个消息正文,采用 JSON 格式。此模板会覆盖整个消息正文。如果您想使用此特定模板,则不能覆盖消息正文。任何手动完成的覆盖都将优先于模板。

有关以下内容的更多信息: