I am generating a link to grafana dashboard from alerts.
Bottom line, I have to convert .StartsAt to from= and to= in grafana url.
I want to do the following:
{{- .Annotations.URL -}}&from={{- sub .StartsAt.Unix 3600 }}&to={{- .StartsAt.Unix -}}
Create a link to the dashboard url from 1 hour before the alert, so users can nicely navigate the dashboard in the proper time interval.
However, when provisioning the template with terraform, this fails with the message:
│ Error: [PUT /v1/provisioning/templates/{name}][400] putTemplateBadRequest {"message":"invalid object specification: invalid template: template: kc:84: function \"sub\" not defined"}
How am I should I create a link to the dashboard so it properly allows users to analyze the event using the data there were there for the alert to generate?
How to create a link to grafana dashboard from alert that shows data between 1 hour before the alert was generated?
So StartsAt is an object, and you can actually call an arbitrary object methos in go template. And it happens Time object has Add and Sub methods, and duration is in milliseconds.
As of Grafana 12, when linking an alert rule to a dashboard panel, the DashboardURL and PanelURL values included in notifications will automatically contain the from and to query params, with time range from 1h before the alert started.
Also, here’s another example similar to the one shared earlier in this thread—thanks to @kamilcuk for contributing this helpful solution to the community!
{{- $from := (.StartsAt.Add -3600000000000).UnixMilli }}
{{- $to := "" }}
{{- if eq .Status "resolved" }}
{{- $to = (.EndsAt).UnixMilli }}
{{- else -}}
{{/* Use current time if alert is firing */}}
{{- $to = (time.Now).UnixMilli }}
{{- end -}}
Dashboard: {{.Annotations.MyDashboardURL}}?from={{$from}}&to={{$to}}