Grafana: Provisioning Alerting Resources
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Checked on 2026-11-09 against Grafana 13.3.x. Tested with Grafana Enterprise 13.3.0 in the hands-on lab: the complete YAML file below is the lab’s rule file: it loads, the Admin API reload applies a changed file, and the export returns the same keys; the HCL passes terraform validate with provider 4.54.0 (it was not applied).
Alerting configuration is the most fragile part of a monitoring setup: it is clicked together once, nobody remembers which rule routes where, and it is lost with the database. Grafana can take every alerting resource from files, from an HTTP API or from Terraform, and can export what already exists in the same formats. This page shows the options, what "provisioned" means for the user interface, and then the complete alerting configuration of the Bookshelf lab, twice: once as provisioning YAML and once as Terraform HCL. The tool-neutral argument for putting observability in Git, and the pipeline around it, is in Observability as Code; dashboards as code is in Grafana: Dashboards as Code.
The resources used here are explained on their own pages and are only applied here: Alert Rules, Evaluation and Missing Data, Labels and Annotations, Notification Policies, Contact Points, Notification Templates and Mute Timings.
The options
| Option | Use it when | Watch out for |
|---|---|---|
File provisioning ( |
Grafana is self-managed (including Docker and Kubernetes) and the files ship with the image or a volume. |
Not available in Grafana Cloud. Provisioned resources cannot be edited in the UI. |
Terraform ( |
You want plan and apply, drift detection and one tool for folders, data sources and alerting; works for Cloud too. |
The provider needs an API token with the alerting provisioning roles; state can hold secrets. |
Alerting provisioning HTTP API |
Scripts and CI jobs that create, change or delete Grafana-managed resources. |
Its JSON is not the file or Terraform format; the contact point, policy, template and mute timing endpoints are deprecated. |
Notifications and rules APIs ( |
New integrations and |
Beta API version ( |
Export (UI and |
Starting from what already exists: build in the UI, export as YAML, JSON or HCL, commit. |
The export format cannot be sent back to the HTTP API; notification template groups have no export. |
Data source-managed rules (including their recording rules) are not part of these options; they are managed with the Mimir or Cortex tools (see Recording Rules).
Provenance: why provisioned resources are read-only
Every resource has a provenance. Resources created through the HTTP API report "provenance": "api", file-provisioned
ones "file", and the user interface labels them Provisioned. Provisioned resources can be edited only at their
source: a rule from a file cannot be changed in the UI or in Terraform, and the reverse. That protects the code from
silent drift, and it is also the first thing users hit when they try to "just quickly fix" a threshold during an
incident. Two escape hatches exist, both of which give up the protection: the X-Disable-Provenance: true header on
the create and update requests of the HTTP API, and disable_provenance = true on the Terraform resources. Importing a
resource that already exists causes a conflict, so remove the existing one first.
Source: Grafana: Provision Alerting resources
and Grafana: Alerting provisioning HTTP API
(provenance and the X-Disable-Provenance header).
The Bookshelf alerting configuration
The lab defines these resources, using the values of the other lab pages: data source uids prometheus and loki,
the label application="bookshelf", the folder bookshelf, the team label bookshelf-sre and the dashboard
"Bookshelf service health" (uid bookshelf-service-health).
| Resource | Definition |
|---|---|
Folder |
|
Rule group |
|
Rule group |
|
Contact point |
A webhook to the lab receiver, with title and message from the template group |
Notification policy tree |
Default policy to |
Message template |
|
Mute timing |
Saturday and Sunday, UTC. |
How the numbers were chosen: 0.05 is a deliberately noisy lab threshold so the alert fires within minutes under load;
0.5 s is the lab latency SLO; the burn rate rule assumes a 99.5 percent availability objective (error budget 0.005), so
a fast burn of 14.4 times the budget is a ratio of 0.072 in both the 1 hour and the 5 minute window, following the
multiwindow pattern of the SRE workbook (see SLIs, SLOs and Error Budgets).
The p95 rule needs histogram buckets, which Micrometer publishes only when percentile histograms are enabled for
http.server.requests (see Metrics and Observability).
Every rule is a three or five step pipeline: instant queries (A, and B for the second window of the burn rate rule),
a Reduce expression that turns each result into one number, and a Threshold (or Math) expression that is the
condition. The No Data and Error handling is chosen per rule: the ratio, latency and log rules use OK for No Data
because "no traffic" or "no error lines" is not an incident, and the dedicated no-data rule uses Alerting because the
absence of the up series is exactly what it exists to detect (see
Rule Evaluation, States and Missing Data).
The labels application, team and severity are on every rule (the last two route), the 5xx rule links to its dashboard panel with the annotations
__dashboardUid__ and __panelId__, and the runbook lives in an annotation, so the policy tree
and the message template need no other input (see Designing Actionable Alerts).
Create the folder first
File provisioning of rules refers to the folder by name and creates it with a generated uid when it is missing, which is
what happens in the lab. Terraform and the API refer to it by uid, so where the uid must be known create the folder once
beforehand, for example through the folder API of the /apis family (basic authentication with the admin account):
curl -s -u admin:admin -X POST -H 'Content-Type: application/json' \
http://localhost:3000/apis/folder.grafana.app/v1/namespaces/default/folders \
-d '{"metadata":{"name":"bookshelf"},"spec":{"title":"bookshelf"}}'
Reference: Grafana: Folder API. Terraform creates it itself (see below).
File provisioning
Put YAML or JSON files in the provisioning/alerting directory of the instance and restart Grafana, or reload them with
the Admin API. In the lab Compose file mount the directory read-only at /etc/grafana/provisioning/alerting. The file
format has one top-level key per resource type, each with its own deleteX counterpart for removals.
The complete file
# provisioning/alerting/bookshelf.yaml
apiVersion: 1
groups:
- orgId: 1
name: bookshelf-service-level
folder: bookshelf
interval: 1m
rules:
- uid: bookshelf-5xx-ratio
title: Bookshelf high 5xx ratio
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: prometheus
model:
datasource: { type: prometheus, uid: prometheus }
editorMode: code
expr: 'sum(rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[5m])) / sum(rate(http_server_requests_seconds_count{application="bookshelf"}[5m]))'
instant: true
range: false
intervalMs: 1000
maxDataPoints: 43200
refId: A
- refId: B
relativeTimeRange: { from: 0, to: 0 }
datasourceUid: __expr__
model:
datasource: { type: __expr__, uid: __expr__ }
expression: A
reducer: last
settings: { mode: dropNN }
refId: B
type: reduce
- refId: C
relativeTimeRange: { from: 0, to: 0 }
datasourceUid: __expr__
model:
datasource: { type: __expr__, uid: __expr__ }
expression: B
conditions:
- evaluator: { type: gt, params: [0.05] }
operator: { type: and }
query: { params: [C] }
reducer: { type: last, params: [] }
type: query
refId: C
type: threshold
noDataState: OK
execErrState: Error
for: 2m
isPaused: false
annotations:
summary: 'Bookshelf 5xx ratio is {{ printf "%.1f" $values.B.Value }} (threshold 0.05)'
description: 'More than 5 percent of Bookshelf requests answered with a 5xx status for 2 minutes.'
runbook_url: https://example.com/runbooks/bookshelf-5xx-ratio
__dashboardUid__: bookshelf-service-health
__panelId__: '2'
labels:
application: bookshelf
team: bookshelf-sre
severity: critical
- uid: bookshelf-p95-latency
title: Bookshelf p95 latency above SLO
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: prometheus
model:
datasource: { type: prometheus, uid: prometheus }
editorMode: code
expr: 'histogram_quantile(0.95, sum by (le) (rate(http_server_requests_seconds_bucket{application="bookshelf"}[5m])))'
instant: true
range: false
intervalMs: 1000
maxDataPoints: 43200
refId: A
- refId: B
relativeTimeRange: { from: 0, to: 0 }
datasourceUid: __expr__
model:
datasource: { type: __expr__, uid: __expr__ }
expression: A
reducer: last
settings: { mode: dropNN }
refId: B
type: reduce
- refId: C
relativeTimeRange: { from: 0, to: 0 }
datasourceUid: __expr__
model:
datasource: { type: __expr__, uid: __expr__ }
expression: B
conditions:
- evaluator: { type: gt, params: [0.5] }
operator: { type: and }
query: { params: [C] }
reducer: { type: last, params: [] }
type: query
refId: C
type: threshold
noDataState: OK
execErrState: Error
for: 5m
isPaused: false
annotations:
summary: 'Bookshelf p95 latency is {{ printf "%.2f" $values.B.Value }} s (SLO 0.5 s)'
description: 'The 95th percentile of Bookshelf request latency has been above the 0.5 s objective for 5 minutes.'
runbook_url: https://example.com/runbooks/bookshelf-latency
labels:
application: bookshelf
team: bookshelf-sre
severity: warning
- uid: bookshelf-slo-burn-rate
title: Bookshelf SLO burn rate
condition: E
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: prometheus
model:
datasource: { type: prometheus, uid: prometheus }
editorMode: code
expr: 'sum(rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[1h])) / sum(rate(http_server_requests_seconds_count{application="bookshelf"}[1h]))'
instant: true
range: false
intervalMs: 1000
maxDataPoints: 43200
refId: A
- refId: B
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: prometheus
model:
datasource: { type: prometheus, uid: prometheus }
editorMode: code
expr: 'sum(rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[5m])) / sum(rate(http_server_requests_seconds_count{application="bookshelf"}[5m]))'
instant: true
range: false
intervalMs: 1000
maxDataPoints: 43200
refId: B
- refId: C
relativeTimeRange: { from: 0, to: 0 }
datasourceUid: __expr__
model:
datasource: { type: __expr__, uid: __expr__ }
expression: A
reducer: last
settings: { mode: dropNN }
refId: C
type: reduce
- refId: D
relativeTimeRange: { from: 0, to: 0 }
datasourceUid: __expr__
model:
datasource: { type: __expr__, uid: __expr__ }
expression: B
reducer: last
settings: { mode: dropNN }
refId: D
type: reduce
- refId: E
relativeTimeRange: { from: 0, to: 0 }
datasourceUid: __expr__
model:
datasource: { type: __expr__, uid: __expr__ }
expression: '$C > 0.072 && $D > 0.072'
refId: E
type: math
noDataState: OK
execErrState: Error
for: 2m
keepFiringFor: 5m
isPaused: false
annotations:
summary: 'Bookshelf burns its error budget 14.4 times too fast (1h {{ printf "%.3f" $values.C.Value }}, 5m {{ printf "%.3f" $values.D.Value }})'
description: 'The 5xx ratio exceeds 0.072 in both the 1 hour and the 5 minute window, a 14.4x burn of a 99.5 percent availability objective.'
runbook_url: https://example.com/runbooks/bookshelf-slo-burn
labels:
application: bookshelf
team: bookshelf-sre
severity: critical
- orgId: 1
name: bookshelf-availability-and-logs
folder: bookshelf
interval: 1m
rules:
- uid: bookshelf-no-data
title: Bookshelf no data
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: prometheus
model:
datasource: { type: prometheus, uid: prometheus }
editorMode: code
expr: 'max(up{job="bookshelf"})'
instant: true
range: false
intervalMs: 1000
maxDataPoints: 43200
refId: A
- refId: B
relativeTimeRange: { from: 0, to: 0 }
datasourceUid: __expr__
model:
datasource: { type: __expr__, uid: __expr__ }
expression: A
reducer: last
settings: { mode: dropNN }
refId: B
type: reduce
- refId: C
relativeTimeRange: { from: 0, to: 0 }
datasourceUid: __expr__
model:
datasource: { type: __expr__, uid: __expr__ }
expression: B
conditions:
- evaluator: { type: lt, params: [1] }
operator: { type: and }
query: { params: [C] }
reducer: { type: last, params: [] }
type: query
refId: C
type: threshold
noDataState: Alerting
execErrState: Error
for: 2m
isPaused: false
annotations:
summary: 'Bookshelf is not reporting metrics or is down'
description: 'The up series for job bookshelf is missing or 0 for 2 minutes.'
runbook_url: https://example.com/runbooks/bookshelf-no-data
labels:
application: bookshelf
team: bookshelf-sre
severity: critical
- uid: bookshelf-error-log-spike
title: Bookshelf error-log spike
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: loki
model:
datasource: { type: loki, uid: loki }
editorMode: code
expr: 'sum(count_over_time({application="bookshelf"} | json | level="ERROR" [5m]))'
queryType: instant
intervalMs: 1000
maxDataPoints: 43200
refId: A
- refId: B
relativeTimeRange: { from: 0, to: 0 }
datasourceUid: __expr__
model:
datasource: { type: __expr__, uid: __expr__ }
expression: A
reducer: last
settings: { mode: dropNN }
refId: B
type: reduce
- refId: C
relativeTimeRange: { from: 0, to: 0 }
datasourceUid: __expr__
model:
datasource: { type: __expr__, uid: __expr__ }
expression: B
conditions:
- evaluator: { type: gt, params: [20] }
operator: { type: and }
query: { params: [C] }
reducer: { type: last, params: [] }
type: query
refId: C
type: threshold
noDataState: OK
execErrState: Error
for: 1m
isPaused: false
annotations:
summary: 'Bookshelf logged {{ printf "%.0f" $values.B.Value }} ERROR lines in 5 minutes'
description: 'More than 20 ERROR log lines in 5 minutes, counted in Loki from the JSON logs of the service.'
runbook_url: https://example.com/runbooks/bookshelf-error-logs
labels:
application: bookshelf
team: bookshelf-sre
severity: warning
contactPoints:
- orgId: 1
name: bookshelf-webhook
receivers:
- uid: bookshelf-webhook
type: webhook
disableResolveMessage: false
settings:
url: http://webhook-receiver:8080/grafana
httpMethod: POST
title: '{{ template "bookshelf.title" . }}'
message: '{{ template "bookshelf.message" . }}'
templates:
- orgId: 1
name: bookshelf
template: |
{{ define "bookshelf.title" -}}
[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}
{{- end }}
{{ define "bookshelf.message" -}}
{{ range .Alerts -}}
* {{ .Labels.alertname }} ({{ .Labels.severity }}): {{ .Annotations.summary }}
{{ if .Annotations.runbook_url }}Runbook: {{ .Annotations.runbook_url }}{{ end }}
{{ end -}}
{{- end }}
muteTimes:
- orgId: 1
name: bookshelf-weekends
time_intervals:
- weekdays: ['saturday', 'sunday']
location: 'UTC'
policies:
- orgId: 1
receiver: bookshelf-webhook
group_by: ['alertname', 'grafana_folder']
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
routes:
- receiver: bookshelf-webhook
object_matchers:
- ['team', '=', 'bookshelf-sre']
routes:
- receiver: bookshelf-webhook
object_matchers:
- ['severity', '=', 'critical']
group_wait: 10s
group_interval: 1m
repeat_interval: 1h
- receiver: bookshelf-webhook
object_matchers:
- ['severity', '=', 'warning']
mute_time_intervals:
- bookshelf-weekends
repeat_interval: 12h
Reference: Grafana: Provision Alerting resources with files
(rules, contact points, templates, policies and mute timings); the expression model keys follow the export format of
the same rules (see the export section below).
Notes on the file format
-
Which values are interpolated.
$VARIABLEin a value is replaced by the environment variable (or an empty string), and a literal dollar sign is written$$. Most properties are interpolated, but not rule annotations, the rule time range, the querymodel, the mute timing name and intervals and the template group name and content. That is why the Go templates in the annotations and the template group, and$C > 0.072in the Math expression, are written with a single$, while a contact point setting that contained a template with$labelswould need$$labels. Secrets belong in environment variables referenced as$WEBHOOK_PASSWORDin contact point settings. -
The policy tree is one resource. Provisioning
policiesoverwrites the whole tree and you cannot provision parts of it; policies that Grafana creates internally when a rule selects a contact point directly are not affected. A policy list can be reset withresetPolicies: [1]. -
Uids. A rule or receiver
uidis at most 40 characters of letters, numbers,-and_. Keep them stable, because changing a uid is deleting one resource and creating another (history and state are lost). -
Removals. Deleting a file does not delete its resources. Use
deleteRules,deleteContactPoints,deleteTemplatesanddeleteMuteTimesentries (each addressed byorgIdanduidorname). -
Rule fields.
for,keepFiringFor,noDataState,execErrState,isPaused,annotations,labelsand the per-queryrelativeTimeRange(fromandtoin seconds before the evaluation) are the field names of the rule export. A rule may setnotification_settingsinstead of relying on the tree, and recording rules use arecordblock (see Recording Rules).
Source: Grafana: Provision Alerting resources with files
(environment variable interpolation) and the Grafana source
provisioning_alert_rules.go
(AlertRuleExport, keepFiringFor, isPaused, relativeTimeRange).
Apply and reload
Restarting Grafana applies the files. To apply changes without a restart use the Admin API, which works only with basic
authentication of a user that has the provisioning:reload action on the provisioners:alerting scope:
curl -s -u admin:admin -X POST http://localhost:3000/api/admin/provisioning/alerting/reload
Reference: Grafana: Admin API (reload provisioning configurations).
Terraform
The grafana/grafana provider manages the same resources. The documentation pins >= 4.47.0; the latest release at
the time of writing is 4.54.0. The provider needs a service account token whose role can use the alerting provisioning
API, which is why the lab ci-provisioner service account holds the fixed:alerting.provisioning.* roles (see
Alerting HA and Operations). For
Terraform itself see Getting Started,
Providers, State and
Sensitive Data.
terraform {
required_providers {
grafana = {
source = "grafana/grafana"
version = ">= 4.47.0"
}
}
}
variable "grafana_url" {
type = string
default = "http://localhost:3000"
}
variable "grafana_token" {
type = string
sensitive = true
}
provider "grafana" {
url = var.grafana_url
auth = var.grafana_token
}
Reference: Grafana: Provision Alerting resources with Terraform
(provider configuration). The provider also accepts basic authentication in auth.
The complete configuration
locals {
prom = { type = "prometheus", uid = "prometheus" }
loki = { type = "loki", uid = "loki" }
expr = { type = "__expr__", uid = "__expr__" }
}
resource "grafana_folder" "bookshelf" {
title = "bookshelf"
uid = "bookshelf"
}
resource "grafana_rule_group" "service_level" {
name = "bookshelf-service-level"
folder_uid = grafana_folder.bookshelf.uid
interval_seconds = 60
rule {
uid = "bookshelf-5xx-ratio"
name = "Bookshelf high 5xx ratio"
condition = "C"
for = "2m"
no_data_state = "OK"
exec_err_state = "Error"
is_paused = false
annotations = {
summary = "Bookshelf 5xx ratio is {{ printf \"%.1f\" $values.B.Value }} (threshold 0.05)"
description = "More than 5 percent of Bookshelf requests answered with a 5xx status for 2 minutes."
runbook_url = "https://example.com/runbooks/bookshelf-5xx-ratio"
__dashboardUid__ = "bookshelf-service-health"
__panelId__ = "2"
}
labels = {
application = "bookshelf"
team = "bookshelf-sre"
severity = "critical"
}
data {
ref_id = "A"
datasource_uid = "prometheus"
relative_time_range {
from = 600
to = 0
}
model = jsonencode({
datasource = local.prom
editorMode = "code"
expr = "sum(rate(http_server_requests_seconds_count{application=\"bookshelf\",status=~\"5..\"}[5m])) / sum(rate(http_server_requests_seconds_count{application=\"bookshelf\"}[5m]))"
instant = true
range = false
intervalMs = 1000
maxDataPoints = 43200
refId = "A"
})
}
data {
ref_id = "B"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
datasource = local.expr
expression = "A"
reducer = "last"
settings = { mode = "dropNN" }
refId = "B"
type = "reduce"
})
}
data {
ref_id = "C"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
datasource = local.expr
expression = "B"
conditions = [{
evaluator = { type = "gt", params = [0.05] }
operator = { type = "and" }
query = { params = ["C"] }
reducer = { type = "last", params = [] }
type = "query"
}]
refId = "C"
type = "threshold"
})
}
}
rule {
uid = "bookshelf-p95-latency"
name = "Bookshelf p95 latency above SLO"
condition = "C"
for = "5m"
no_data_state = "OK"
exec_err_state = "Error"
is_paused = false
annotations = {
summary = "Bookshelf p95 latency is {{ printf \"%.2f\" $values.B.Value }} s (SLO 0.5 s)"
description = "The 95th percentile of Bookshelf request latency has been above the 0.5 s objective for 5 minutes."
runbook_url = "https://example.com/runbooks/bookshelf-latency"
}
labels = {
application = "bookshelf"
team = "bookshelf-sre"
severity = "warning"
}
data {
ref_id = "A"
datasource_uid = "prometheus"
relative_time_range {
from = 600
to = 0
}
model = jsonencode({
datasource = local.prom
editorMode = "code"
expr = "histogram_quantile(0.95, sum by (le) (rate(http_server_requests_seconds_bucket{application=\"bookshelf\"}[5m])))"
instant = true
range = false
intervalMs = 1000
maxDataPoints = 43200
refId = "A"
})
}
data {
ref_id = "B"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
datasource = local.expr
expression = "A"
reducer = "last"
settings = { mode = "dropNN" }
refId = "B"
type = "reduce"
})
}
data {
ref_id = "C"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
datasource = local.expr
expression = "B"
conditions = [{
evaluator = { type = "gt", params = [0.5] }
operator = { type = "and" }
query = { params = ["C"] }
reducer = { type = "last", params = [] }
type = "query"
}]
refId = "C"
type = "threshold"
})
}
}
rule {
uid = "bookshelf-slo-burn-rate"
name = "Bookshelf SLO burn rate"
condition = "E"
for = "2m"
keep_firing_for = "5m"
no_data_state = "OK"
exec_err_state = "Error"
is_paused = false
annotations = {
summary = "Bookshelf burns its error budget 14.4 times too fast (1h {{ printf \"%.3f\" $values.C.Value }}, 5m {{ printf \"%.3f\" $values.D.Value }})"
description = "The 5xx ratio exceeds 0.072 in both the 1 hour and the 5 minute window, a 14.4x burn of a 99.5 percent availability objective."
runbook_url = "https://example.com/runbooks/bookshelf-slo-burn"
}
labels = {
application = "bookshelf"
team = "bookshelf-sre"
severity = "critical"
}
data {
ref_id = "A"
datasource_uid = "prometheus"
relative_time_range {
from = 600
to = 0
}
model = jsonencode({
datasource = local.prom
editorMode = "code"
expr = "sum(rate(http_server_requests_seconds_count{application=\"bookshelf\",status=~\"5..\"}[1h])) / sum(rate(http_server_requests_seconds_count{application=\"bookshelf\"}[1h]))"
instant = true
range = false
intervalMs = 1000
maxDataPoints = 43200
refId = "A"
})
}
data {
ref_id = "B"
datasource_uid = "prometheus"
relative_time_range {
from = 600
to = 0
}
model = jsonencode({
datasource = local.prom
editorMode = "code"
expr = "sum(rate(http_server_requests_seconds_count{application=\"bookshelf\",status=~\"5..\"}[5m])) / sum(rate(http_server_requests_seconds_count{application=\"bookshelf\"}[5m]))"
instant = true
range = false
intervalMs = 1000
maxDataPoints = 43200
refId = "B"
})
}
data {
ref_id = "C"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
datasource = local.expr
expression = "A"
reducer = "last"
settings = { mode = "dropNN" }
refId = "C"
type = "reduce"
})
}
data {
ref_id = "D"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
datasource = local.expr
expression = "B"
reducer = "last"
settings = { mode = "dropNN" }
refId = "D"
type = "reduce"
})
}
data {
ref_id = "E"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
datasource = local.expr
expression = "$C > 0.072 && $D > 0.072"
refId = "E"
type = "math"
})
}
}
}
resource "grafana_rule_group" "availability_and_logs" {
name = "bookshelf-availability-and-logs"
folder_uid = grafana_folder.bookshelf.uid
interval_seconds = 60
rule {
uid = "bookshelf-no-data"
name = "Bookshelf no data"
condition = "C"
for = "2m"
no_data_state = "Alerting"
exec_err_state = "Error"
is_paused = false
annotations = {
summary = "Bookshelf is not reporting metrics or is down"
description = "The up series for job bookshelf is missing or 0 for 2 minutes."
runbook_url = "https://example.com/runbooks/bookshelf-no-data"
}
labels = {
application = "bookshelf"
team = "bookshelf-sre"
severity = "critical"
}
data {
ref_id = "A"
datasource_uid = "prometheus"
relative_time_range {
from = 600
to = 0
}
model = jsonencode({
datasource = local.prom
editorMode = "code"
expr = "max(up{job=\"bookshelf\"})"
instant = true
range = false
intervalMs = 1000
maxDataPoints = 43200
refId = "A"
})
}
data {
ref_id = "B"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
datasource = local.expr
expression = "A"
reducer = "last"
settings = { mode = "dropNN" }
refId = "B"
type = "reduce"
})
}
data {
ref_id = "C"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
datasource = local.expr
expression = "B"
conditions = [{
evaluator = { type = "lt", params = [1] }
operator = { type = "and" }
query = { params = ["C"] }
reducer = { type = "last", params = [] }
type = "query"
}]
refId = "C"
type = "threshold"
})
}
}
rule {
uid = "bookshelf-error-log-spike"
name = "Bookshelf error-log spike"
condition = "C"
for = "1m"
no_data_state = "OK"
exec_err_state = "Error"
is_paused = false
annotations = {
summary = "Bookshelf logged {{ printf \"%.0f\" $values.B.Value }} ERROR lines in 5 minutes"
description = "More than 20 ERROR log lines in 5 minutes, counted in Loki from the JSON logs of the service."
runbook_url = "https://example.com/runbooks/bookshelf-error-logs"
}
labels = {
application = "bookshelf"
team = "bookshelf-sre"
severity = "warning"
}
data {
ref_id = "A"
datasource_uid = "loki"
relative_time_range {
from = 600
to = 0
}
model = jsonencode({
datasource = local.loki
editorMode = "code"
expr = "sum(count_over_time({application=\"bookshelf\"} | json | level=\"ERROR\" [5m]))"
queryType = "instant"
intervalMs = 1000
maxDataPoints = 43200
refId = "A"
})
}
data {
ref_id = "B"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
datasource = local.expr
expression = "A"
reducer = "last"
settings = { mode = "dropNN" }
refId = "B"
type = "reduce"
})
}
data {
ref_id = "C"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
datasource = local.expr
expression = "B"
conditions = [{
evaluator = { type = "gt", params = [20] }
operator = { type = "and" }
query = { params = ["C"] }
reducer = { type = "last", params = [] }
type = "query"
}]
refId = "C"
type = "threshold"
})
}
}
}
resource "grafana_message_template" "bookshelf" {
name = "bookshelf"
template = <<-EOT
{{ define "bookshelf.title" -}}
[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}
{{- end }}
{{ define "bookshelf.message" -}}
{{ range .Alerts -}}
* {{ .Labels.alertname }} ({{ .Labels.severity }}): {{ .Annotations.summary }}
{{ if .Annotations.runbook_url }}Runbook: {{ .Annotations.runbook_url }}{{ end }}
{{ end -}}
{{- end }}
EOT
}
resource "grafana_contact_point" "bookshelf_webhook" {
name = "bookshelf-webhook"
webhook {
url = "http://webhook-receiver:8080/grafana"
http_method = "POST"
title = "{{ template \"bookshelf.title\" . }}"
message = "{{ template \"bookshelf.message\" . }}"
}
depends_on = [grafana_message_template.bookshelf]
}
resource "grafana_mute_timing" "weekends" {
name = "bookshelf-weekends"
intervals {
weekdays = ["saturday", "sunday"]
location = "UTC"
}
}
resource "grafana_notification_policy" "bookshelf" {
contact_point = grafana_contact_point.bookshelf_webhook.name
group_by = ["alertname", "grafana_folder"]
group_wait = "30s"
group_interval = "5m"
repeat_interval = "4h"
policy {
contact_point = grafana_contact_point.bookshelf_webhook.name
matcher {
label = "team"
match = "="
value = "bookshelf-sre"
}
policy {
contact_point = grafana_contact_point.bookshelf_webhook.name
group_wait = "10s"
group_interval = "1m"
repeat_interval = "1h"
matcher {
label = "severity"
match = "="
value = "critical"
}
}
policy {
contact_point = grafana_contact_point.bookshelf_webhook.name
repeat_interval = "12h"
mute_timings = [grafana_mute_timing.weekends.name]
matcher {
label = "severity"
match = "="
value = "warning"
}
}
}
}
Reference: grafana_rule_group,
grafana_contact_point,
grafana_notification_policy,
grafana_message_template and
grafana_mute_timing; the
webhook block fields (url, http_method, title, message, max_alerts) are in the contact point schema.
Notes on the Terraform resources
-
jsonencodeformodel. The querymodelis a data source specific JSON string. The documentation recommends creating a complex rule in the UI and copying its JSON, and the same applies to Loki and Prometheus fields such aseditorModeandqueryType. Usedatasource_uid = "__expr__"for the expression stages. -
One policy resource.
grafana_notification_policymanages the entire default tree and overwrites it; it does not overwrite internal policies created when rules select a contact point directly. Only one such resource should exist per organization. Notice how the tree refers to the contact point and the mute timing by resource reference, so Terraform creates them first, which is something file provisioning cannot express. -
Quoting. A Go template inside an HCL string needs the inner double quotes escaped, and a
$followed by{would start an HCL interpolation, which is why the rule uses$values.B.Value(no brace) and a heredoc (<<-EOT) holds the template group. -
Optional fields.
keep_firing_for,missing_series_evals_to_resolve,notification_settings(per-rule routing that overrides the tree, needs thealertingSimplifiedRoutingtoggle) andrecord(recording rules, needs thegrafanaManagedRecordingRulestoggle) exist onrule;disable_provenance = trueon any of the resources allows UI edits at the cost of drift. -
Multiple routing trees. Besides the default tree, the provider has
grafana_apps_notifications_routingtree_v1beta1for named trees; a rule routes to one withnotification_settings { policy = ... }, and rules without it stay on the default tree. -
Applying and importing.
terraform init,terraform planandterraform applyas usual. Existing resources are imported with the addresses shown below. See Import and Query and, for a pipeline, CI/CD and Automation.
terraform import grafana_rule_group.name "{{ folderUID }}:{{ title }}"
terraform import grafana_message_template.name "{{ name }}"
terraform import grafana_mute_timing.name "{{ name }}"
Source: Grafana: Provision Alerting resources with Terraform
and the resource pages above (schema of rule, data, notification_settings, policy).
The HTTP API and the new APIs
The alerting provisioning API (/api/v1/provisioning/...) is what the Terraform provider itself uses. Requests carry
Authorization: Bearer <token>, and on Enterprise some endpoints need specific RBAC permissions.
| Resource | Endpoints |
|---|---|
Alert and recording rules |
|
Rule groups |
|
Contact points |
|
Notification policies |
|
Template groups |
|
Mute timings |
|
A recording rule uses the same alert rule endpoint with a record block (metric, from, target_datasource_uid)
instead of condition, and for set to 0s. The X-Disable-Provenance: true header on PUT rule groups, POST alert
rules, contact points and mute timings, PUT templates and PUT policies allows UI editing afterwards. PUT and
DELETE of mute timings and template groups accept an optional version query parameter for optimistic concurrency.
The endpoints for contact points, notification policies, template groups and mute timings are deprecated and will be
removed in a future release, and they do not return resources of a staged Alertmanager import. The documented
replacements are the App Platform APIs, served under /apis with the namespace default for organization 1:
| Resource | Path under /apis/ (version v1beta1) |
|---|---|
Alert rules and recording rules |
|
Contact points |
|
Notification policies |
|
Template groups |
|
Mute timings |
|
# list the contact points through the notifications API (lab: basic authentication)
curl -s -u admin:admin \
http://localhost:3000/apis/notifications.alerting.grafana.app/v1beta1/namespaces/default/receivers
# export the current notification policy tree as YAML through the provisioning API
curl -s -u admin:admin 'http://localhost:3000/api/v1/provisioning/policies/export?format=yaml'
Source: Grafana: Alerting provisioning HTTP API (endpoints, provenance, deprecation notice and replacement paths) and Grafana: The /apis HTTP API.
Exporting existing resources
Starting from the UI is often faster than writing a model by hand: build the rule, then export it. From
Alerts & IRM > Alerting, most resources export as YAML, JSON or Terraform (HCL), with copy or download.
-
Rules: Export rules for all Grafana-managed rules, the folder icon in the List view, or the rule group icon in the Grouped view. More > Modify export edits a rule for export without saving it, and exports the whole group. Export rule definition produces a new rule in HCL only.
-
Contact points: More > Export. Policies: Export on the default policy, or More actions > Export for a named tree. Mute timings: Export on the timing.
-
Template groups have no export; copy the name and content from the Notification templates tab.
The same is available over HTTP with the /api/v1/provisioning/.../export endpoints, whose format parameter (default yaml; also json and
hcl) or Accept header selects the output, and download returns a file:
curl -s -u admin:admin 'http://localhost:3000/api/v1/provisioning/alert-rules/export?format=hcl'
curl -s -u admin:admin 'http://localhost:3000/api/v1/provisioning/folder/bookshelf/rule-groups/bookshelf-service-level/export?format=yaml'
curl -s -u admin:admin 'http://localhost:3000/api/v1/provisioning/contact-points/export?format=yaml'
curl -s -u admin:admin 'http://localhost:3000/api/v1/provisioning/mute-timings/export?format=yaml'
Contact point export accepts a decrypt parameter for secrets and policy export a routeName parameter for named trees;
decrypted export needs the alert.provisioning.secrets:read permission. Exported output is for files and Terraform; it
cannot be sent back to the provisioning API because the request format differs.
Source: Grafana: Export alerting resources
and the HTTP API page above (export endpoints, format, decrypt, routeName).
What can go wrong
| Symptom | Cause and fix |
|---|---|
The rule group fails to load: folder not found |
The folder does not exist yet. Create it first (UI, API or |
After provisioning, a rule shows Error with "datasource not found" |
The |
The notification policy tree was replaced and an old route vanished |
The tree is a single resource; a second source (UI, another file or Terraform) overwrote or was overwritten. Keep exactly one owner. |
The UI will not let you edit a rule, contact point or policy |
It is provisioned. Edit the file or Terraform code, or recreate the resource with |
A resource still exists after its file was removed |
Files add and update only; add the matching |
A mute timing is not applied |
The name in |
A |
Environment interpolation consumed it; write |
Terraform plan keeps showing a diff on |
The JSON differs from what Grafana stores. Use the exported JSON as the starting point. |
Enforcement rejects a write |
Alert Advisor is enforced and the rule lacks a required label or annotation (see Alerting HA and Operations). |
Verify in the lab
-
Save the YAML as
provisioning/alerting/bookshelf.yamlin the lab Grafana volume, create the folder, and restart Grafana. Check the log for provisioning errors, then open Alerting > Alert rules: two groups with five rules in the folderbookshelf, each labelled Provisioned. -
Open a rule and try to edit it: the form is read-only. Open Contact points, Notification policies, Notification templates and Mute timings: all four carry the label.
-
Check Notification policies: the default policy with
team = bookshelf-sreand its two children, the one withseverity = warningshowing thebookshelf-weekendsmute timing. -
Run the load generator in failing-request mode and watch
Bookshelf high 5xx ratiogo Pending then Alerting. The lab webhook receiver logs a payload whosetitleandmessagecome from thebookshelftemplate group. -
Stop the Bookshelf container:
Bookshelf no datagoes to Alerting after the pending period, first because theupseries drops to 0 and, once the series disappears from Prometheus, through the No Data handling. -
Export the rule group with the curl command above and compare it with the file; then apply the HCL in a clean lab with
terraform apply(after removing the file) and compare again. The two exports should describe the same rules.
In the books
Chapter 10 of Observability with Grafana (Chapman and Holmes, Packt, 2023) shows grafana_rule_group with a rule
block per alert and suggests a dynamic block to populate the rules from another source such as a JSON file, and it
states that the Ansible collection of the time had not been updated for the new alerting. The Terraform resource is
still the central one, but the book’s snippet is abbreviated and predates the attributes used here (keep_firing_for,
missing_series_evals_to_resolve, notification_settings and named routing trees), the provenance behaviour and the
deprecation of the older provisioning endpoints.