From 230ffb87b8d957316edbf1de8a2a50b7f0092129 Mon Sep 17 00:00:00 2001 From: David Leadbeater Date: Sat, 15 Feb 2020 18:57:20 +0000 Subject: [PATCH] Add templated text support for webhook receivers This can be used to avoid webhook receivers potentially having to reimplement the templating already done in alertmanager. An example configuration using this would look something like: receivers: - name: webhook webhook_configs: - url: http://localhost:1111/alert templates: summary: "{{ .CommonLabels.severity }}: {{ .CommonLabels.alertname }}" The webhook will then receive something like: {...,"templated":{"summary":"page: Test"}} 'templated' is marked as "omitempty" to avoid adding this for receivers who don't configure it, therefore keeping this fully backward compatible. Signed-off-by: David Leadbeater --- config/notifiers.go | 2 ++ notify/webhook/webhook.go | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/config/notifiers.go b/config/notifiers.go index 5db3d66ff6..3766b384f3 100644 --- a/config/notifiers.go +++ b/config/notifiers.go @@ -381,6 +381,8 @@ type WebhookConfig struct { // Alerts exceeding this threshold will be truncated. Setting this to 0 // allows an unlimited number of alerts. MaxAlerts uint64 `yaml:"max_alerts" json:"max_alerts"` + // Optional Go templates for text to expand and then pass to the webhook. + Templates map[string]string `yaml:"templates,omitempty" json:"templates,omitempty"` } // UnmarshalYAML implements the yaml.Unmarshaler interface. diff --git a/notify/webhook/webhook.go b/notify/webhook/webhook.go index f56012d5db..3fdb6aa473 100644 --- a/notify/webhook/webhook.go +++ b/notify/webhook/webhook.go @@ -23,6 +23,7 @@ import ( "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" + "github.com/pkg/errors" commoncfg "github.com/prometheus/common/config" "github.com/prometheus/common/version" @@ -72,6 +73,8 @@ type Message struct { Version string `json:"version"` GroupKey string `json:"groupKey"` TruncatedAlerts uint64 `json:"truncatedAlerts"` + // Expanded text templates. + Templated map[string]string `json:"templated,omitempty"` } func truncateAlerts(maxAlerts uint64, alerts []*types.Alert) ([]*types.Alert, uint64) { @@ -87,6 +90,15 @@ func (n *Notifier) Notify(ctx context.Context, alerts ...*types.Alert) (bool, er alerts, numTruncated := truncateAlerts(n.conf.MaxAlerts, alerts) data := notify.GetTemplateData(ctx, n.tmpl, alerts, n.logger) + templated := map[string]string{} + for name, t := range n.conf.Templates { + text, err := n.tmpl.ExecuteTextString(t, data) + if err != nil { + return false, errors.Wrapf(err, "execute '%s' template", name) + } + templated[name] = text + } + groupKey, err := notify.ExtractGroupKey(ctx) if err != nil { level.Error(n.logger).Log("err", err) @@ -97,6 +109,7 @@ func (n *Notifier) Notify(ctx context.Context, alerts ...*types.Alert) (bool, er Data: data, GroupKey: groupKey.String(), TruncatedAlerts: numTruncated, + Templated: templated, } var buf bytes.Buffer