Sort Alertmanager Email Templates in Go Template

I am trying to customize an email template from AlertManager that uses a Go html template that prints a list of alerts using the following construct:

{{ range .Alerts.Firing }}

It is inserted into the template as follows:

func (n *Email) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
   ...
   data = n.tmpl.Data(receiverName(ctx), groupLabels(ctx), as...)
   ...
}

A warning is defined as follows:

type Alert struct {
    Labels LabelSet `json:"labels"`

    Annotations LabelSet `json:"annotations"`

    StartsAt     time.Time `json:"startsAt,omitempty"`
    EndsAt       time.Time `json:"endsAt,omitempty"`
    GeneratorURL string    `json:"generatorURL"`
}

I would like to do a sort in the StartsAt field.

I tried using the sort function, but it was not available in the email template.

{{ range sort .Alerts.Firing }}

I get

function \"sort\" not defined

Any ideas on how I can sort it by StartsAt?

+4
source share
1 answer

, . , , .

:

type ByStart []*types.Alert

func (a ByStart) Len() int           { return len(a) }
func (a ByStart) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByStart) Less(i, j int) bool { return a[i].StartAt.Before(a[j].StartAt) }

func (n *Email) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
    ...
    sort.Sort(ByStart(as))
    data = n.tmpl.Data(receiverName(ctx), groupLabels(ctx), as...)
    ...
}

Edit:

. , , Go ( , . Template.Funcs()). , , , , .

, , .

+2

Source: https://habr.com/ru/post/1665992/


All Articles