Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add templated text support for webhook receivers #2184

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions config/notifiers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 13 additions & 0 deletions notify/webhook/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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) {
Expand All @@ -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)
Expand All @@ -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
Expand Down