Data and monitoring · Advanced · 30 min
Provision Grafana data sources, alert rules and contact points as code
By Padding · Updated 27 Nov 2026
Ubuntu 26.04 · Grafana 13.3.2 · Prometheus 3.16.0 · Loki 3.7.10
You will have Grafana 13.3 loading its Prometheus and Loki data sources, an alert folder, two alert rules, two webhook contact points with a secret read from a file and a notification policy from YAML files, checked over the HTTP API and proven by a real alert reaching a local receiver.
On this page
The Grafana dashboard tutorial put a data source and a dashboard in files. Alerting is where files matter more. An alert rule clicked together in the browser lives only in Grafana's database: nobody reviews it, you cannot see who changed the threshold last Tuesday, and a rebuilt server has none of it. If you load every rule, contact point and notification policy from YAML at startup, the files are the record. Grafana calls this file provisioning.
You will write five files under /etc/grafana/provisioning:
- Data sources for Prometheus and Loki, each with a fixed
uidthat the rules refer to. - Alert rules in one rule group: a page when Node Exporter stops answering, and a ticket when an application logs too many errors. The rule file also creates the Platform alerts folder they live in.
- Contact points: two webhooks, one for pages and one for tickets. The bearer token they send is read from a private file, so the YAML can go into Git.
- A notification policy that sends
severity=pagealerts to the pager webhook and everything else to the ticket webhook.
Then you load them without restarting Grafana, check each object over the HTTP API, break Node Exporter on purpose and watch the alert arrive at a small receiver on the same server. The last steps export alerts that already exist in a Grafana into files, and remove everything cleanly.
Step 1 · Connect to Grafana's API and see the provisioning folders
Every check in this tutorial goes through Grafana's HTTP API, which answers the same questions as the browser but gives you text you can compare. Install jq for reading the JSON, and Python if your server lacks it:
sudo apt update
sudo apt install -y jq python3Read the admin password into a variable without echoing it. Use the password you set in the dashboard tutorial:
read -rsp "Grafana admin password: " GF_PW; echoThen define a small helper. It hands the login to curl on standard input as a config line, so the password never appears on a command line or in your shell history. Every later command uses it, so stay in this terminal:
gapi() {
printf 'user = "admin:%s"\n' "$GF_PW" | curl -s -K - "$@"
}
gapi http://127.0.0.1:3000/api/health | jq -r .version
gapi -f http://127.0.0.1:3000/api/user | jq -r .login
ls /etc/grafana/provisioningGrafana reads one folder per kind of object. datasources and dashboards you used before. alerting holds rules, contact points, notification policies, mute timings and message templates. Grafana reads every .yaml or .yml file in it, in any order, and a single file may mix kinds; one file per kind is easier to review.
Check it worked
The version line is 13.3.2, or a later 13.3 release. The health endpoint answers without a login, so it only proves Grafana is up; the second line, admin, proves the password works. If the password is wrong, curl -f gives up on the 401 and jq has nothing to read, so the second line is missing: run the read command again. The listing includes alerting, dashboards and datasources.
Step 2 · Provision the Prometheus and Loki data sources
Alert rules name their data source by uid, not by display name, so pin the uid in the file. A rule that says datasourceUid: prometheus then works on every server you build from these files, even if someone renames the data source. Rewrite the Prometheus file from the dashboard tutorial with one addition, timeInterval, which tells Grafana your scrape interval so it never asks Prometheus for steps finer than the data:
sudo tee /etc/grafana/provisioning/datasources/prometheus.yaml > /dev/null <<'YAML'
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://127.0.0.1:9090
isDefault: true
editable: false
jsonData:
timeInterval: 15s
httpMethod: POST
YAMLAdd Loki in a second file. maxLines caps how many lines a log query returns to the browser:
sudo tee /etc/grafana/provisioning/datasources/loki.yaml > /dev/null <<'YAML'
apiVersion: 1
datasources:
- name: Loki
uid: loki
type: loki
access: proxy
url: http://127.0.0.1:3100
editable: false
jsonData:
maxLines: 1000
YAMLGrafana reads provisioning files at startup. Instead of restarting it, ask it to read the data source files again. The reload needs an admin login, which the helper provides. --fail-with-body makes curl exit with an error if Grafana refuses, and still print Grafana's JSON message saying why:
gapi --fail-with-body -X POST http://127.0.0.1:3000/api/admin/provisioning/datasources/reload
echoThe answer is a short JSON message saying the data sources were reloaded. A YAML mistake is reported in Grafana's log, which you read with sudo journalctl -u grafana-server -n 30 --no-pager.
Check it worked
Ask Grafana to test both connections:
gapi http://127.0.0.1:3000/api/datasources/uid/prometheus/health | jq -r .status
gapi http://127.0.0.1:3000/api/datasources/uid/loki/health | jq -r .status
gapi http://127.0.0.1:3000/api/datasources/uid/prometheus | jq -r .jsonData.timeIntervalThe first two lines are OK and the third is 15s. If Loki shows ERROR, check that Loki is running with curl -s http://127.0.0.1:3100/ready, which prints ready.
Step 3 · Start a stand-in receiver for notifications
Before Grafana can send anything, something must be listening. In production a webhook contact point posts to a chat tool, an on-call service or an SMS gateway. Here a 30-line Python server plays that part. It does what a careful receiver does: it rejects any request without the right bearer token, and for accepted ones it prints the path, the alert's status, name, severity and summary.
If your on-call people rely on phones with patchy or prepaid data, a webhook into a chat app or SMS gateway they already use usually reaches them faster than email; any service that accepts a JSON POST works with the same contact point type.
Make a demo folder and a token. The receiver's owner normally issues the token; here you create one:
mkdir -p ~/grafana-alerts-demo
cd ~/grafana-alerts-demo
WH_TOKEN="$(python3 -c 'import secrets; print(secrets.token_hex(24))')"Write the receiver:
cat > ~/grafana-alerts-demo/receiver.py <<'PY'
import hmac
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
EXPECTED = "Bearer " + os.environ["WEBHOOK_TOKEN"]
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
auth = self.headers.get("Authorization", "")
if not hmac.compare_digest(auth.encode(), EXPECTED.encode()):
print(self.path, "rejected: missing or wrong token", flush=True)
self.send_response(401)
self.end_headers()
return
for alert in json.loads(body).get("alerts", []):
print(
self.path,
alert["status"],
alert["labels"].get("alertname"),
alert["labels"].get("severity"),
"-",
alert["annotations"].get("summary"),
flush=True,
)
self.send_response(200)
self.end_headers()
def log_message(self, *args):
pass
HTTPServer(("127.0.0.1", 5001), Handler).serve_forever()
PYStart it in the background. The token reaches it as an environment variable, which does not show in the process list the way an argument would:
WEBHOOK_TOKEN="$WH_TOKEN" nohup python3 ~/grafana-alerts-demo/receiver.py > ~/grafana-alerts-demo/receiver.log 2>&1 &
sleep 1Check it worked
Send it a request with no token:
curl -s -o /dev/null -w '%{http_code}\n' -X POST -d '{}' http://127.0.0.1:5001/page
cat ~/grafana-alerts-demo/receiver.logThe first line is 401, and the log says /page rejected: missing or wrong token. The receiver is up and refuses strangers.
Step 4 · Write the contact points with the token in a file
Store the token where Grafana can read it and other users cannot. As in the dashboard tutorial, the file is created with its final owner and mode first, and printf is a shell built-in, so the token never appears in a process list:
sudo install -m 640 -o root -g grafana /dev/null /etc/grafana/webhook_token
printf '%s' "$WH_TOKEN" | sudo tee /etc/grafana/webhook_token > /dev/null
sudo ls -l /etc/grafana/webhook_tokenIf you were given a token by a real service, read it with read -rsp "Token: " WH_TOKEN; echo and run the same two commands.
Now the contact points. Grafana expands $__file{path} in provisioning files: it replaces the expression with the file's contents, trimmed of the trailing newline. The YAML you commit only says where the secret lives. Each receiver has a uid, which is how later files, including the removal file at the end, refer to it:
sudo tee /etc/grafana/provisioning/alerting/contact-points.yaml > /dev/null <<'YAML'
apiVersion: 1
contactPoints:
- orgId: 1
name: ops-pager
receivers:
- uid: ops-pager-webhook
type: webhook
settings:
url: http://127.0.0.1:5001/page
httpMethod: POST
authorization_scheme: Bearer
authorization_credentials: $__file{/etc/grafana/webhook_token}
- orgId: 1
name: ops-tickets
receivers:
- uid: ops-tickets-webhook
type: webhook
settings:
url: http://127.0.0.1:5001/ticket
httpMethod: POST
authorization_scheme: Bearer
authorization_credentials: $__file{/etc/grafana/webhook_token}
YAMLEvery $ in a provisioning file is a candidate for expansion, including $VAR environment variables. If a setting needs a literal dollar sign, write $$.
Check it worked
ls -l shows -rw-r----- with owner root and group grafana. Grafana has not read the contact point file yet; the next steps add the rules and the policy, then load all three together.
Step 5 · Write the alert rules and their folder
A Grafana-managed rule is a small pipeline of steps, each with a refId. Step A is a query against a data source. Step C is a server-side expression (data source __expr__) that turns the result into true or false. condition: C says which step decides whether the alert fires. The query model sits under model in the same shape the browser saves, which is why exporting a rule (later in this tutorial) is the easiest way to learn it.
This file holds one rule group, server-health, evaluated every 30 seconds. folder: Platform alerts names the folder the group lives in; Grafana creates it on the first load if it does not exist, so the folder is code too:
sudo tee /etc/grafana/provisioning/alerting/rules.yaml > /dev/null <<'YAML'
apiVersion: 1
groups:
- orgId: 1
name: server-health
folder: Platform alerts
interval: 30s
rules:
- uid: node-exporter-down
title: Node Exporter down
condition: C
data:
- refId: A
relativeTimeRange:
from: 300
to: 0
datasourceUid: prometheus
model:
refId: A
expr: up{job="node"}
instant: true
- refId: C
datasourceUid: __expr__
model:
refId: C
type: threshold
expression: A
conditions:
- evaluator:
type: lt
params: [1]
noDataState: Alerting
execErrState: Error
for: 1m
labels:
severity: page
annotations:
summary: Node Exporter on {{ $labels.instance }} is not answering scrapes
runbook_url: https://wiki.example.com/runbooks/node-exporter-down
- uid: demo-app-error-logs
title: Error log lines in demo-app
condition: C
data:
- refId: A
relativeTimeRange:
from: 300
to: 0
datasourceUid: loki
model:
refId: A
expr: sum(count_over_time({job="demo-app"} |= "error" [5m]))
queryType: instant
- refId: C
datasourceUid: __expr__
model:
refId: C
type: threshold
expression: A
conditions:
- evaluator:
type: gt
params: [20]
noDataState: OK
execErrState: Error
for: 5m
labels:
severity: ticket
annotations:
summary: demo-app logged more than 20 error lines in 5 minutes
YAMLWhat the less obvious fields do:
instant: trueasks Prometheus for the latest value of each series, so the threshold compares one number per target.upis1when the last scrape worked and0when it failed, solt 1fires for a target that is down.foris the pending period: the condition must hold on every evaluation for that long before the alert fires. One minute rides out a single missed scrape.noDataStatedecides what an empty result means. For the Node Exporter rule, noupseries at all means Prometheus lost the target, which deserves a page, so it isAlerting. For the log rule, no matching lines is the good case, so it isOK.execErrState: Errormakes a broken query show as an error alert instead of silently passing.labelscarryseverity, which the notification policy routes on. Grafana addsalertname(the title) andgrafana_folderitself, plus the query's own labels such asinstance.annotationsare message text.{{ $labels.instance }}is filled in when the alert fires; provisioning does not expand$inside annotations or query models, so you do not need$$there.- The
uidvalues are yours to choose (letters, digits,-and_, up to 40 characters). Keep them stable: they are how Grafana knows that an edited rule is the same rule.
Replace the runbook_url with a page your team keeps. The paging tutorial covers what a one-page runbook should hold.
Check it worked
The rules name the data source uids you provisioned, spelled exactly as in the data source files:
grep -E 'datasourceUid: (prometheus|loki)$' /etc/grafana/provisioning/alerting/rules.yamlThe grep prints two lines, one per data source.
Step 6 · Write the notification policy and load everything
The notification policy tree decides which contact point gets each alert. The top of the tree is the default: anything no child route matches goes there. This one sends everything to the ticket webhook, except alerts labelled severity=page, which go to the pager quickly and repeat more often while they stay unresolved.
Read this warning before you write the file: a provisioned policy file replaces the whole tree. Any routes someone added in the browser are removed when Grafana loads it. If this Grafana already has routes you want, export them first (see the export step below) and merge them into this file.
sudo tee /etc/grafana/provisioning/alerting/policies.yaml > /dev/null <<'YAML'
apiVersion: 1
policies:
- orgId: 1
receiver: ops-tickets
group_by: [grafana_folder, alertname]
group_wait: 30s
group_interval: 5m
repeat_interval: 12h
routes:
- receiver: ops-pager
object_matchers:
- [severity, =, page]
group_wait: 10s
group_interval: 1m
repeat_interval: 4h
YAMLgroup_bybundles alerts with the same folder and name into one notification, so ten hosts going down at once send one message, not ten.group_waitis how long a new group waits for company before the first message;group_intervalspaces follow-up messages for a group that changed (including the "resolved" message);repeat_intervalre-sends a group that is still firing.object_matchersuse[label, operator, value];=,!=,=~and!~are the operators.
Load the three alerting files. Grafana applies them in a fixed order whatever the file names: contact points first, then the policy that refers to them, then the rules:
gapi --fail-with-body -X POST http://127.0.0.1:3000/api/admin/provisioning/alerting/reload
echoA restart (sudo systemctl restart grafana-server) loads them as well. Either way, a mistake such as a policy naming a contact point that does not exist is reported in Grafana's log. With the reload, curl also prints Grafana's error message in place of the success message and exits with a non-zero status.
Check it worked
List what Grafana now holds. provenance shows who manages each object; file means a provisioning file does, and Grafana refuses edits to it from the browser and the normal API:
gapi http://127.0.0.1:3000/api/v1/provisioning/alert-rules | jq -r '.[] | "\(.title) | \(.ruleGroup) | \(.provenance)"'
gapi http://127.0.0.1:3000/api/folders | jq -r '.[].title'
gapi http://127.0.0.1:3000/api/v1/provisioning/contact-points | jq -r '.[] | "\(.name) \(.settings.url // "") \(.settings.authorization_credentials // "")"'
gapi http://127.0.0.1:3000/api/v1/provisioning/policies | jq -c '{receiver, routes: [.routes[] | {receiver, object_matchers}]}'You see:
- the two rule titles, each with
server-health | file; Platform alertsamong the folders;ops-pagerandops-ticketswith their URLs (Grafana's built-in default email contact point is listed too). The credential is not shown: Grafana prints a placeholder, something like[REDACTED], in place of the token;- the policy with
"receiver":"ops-tickets"and one route toops-pagermatchingseverity = page.
In the browser, Alerting, then Alert rules, shows both rules under Platform alerts with a provisioned badge and no edit option.
Step 7 · Fire a real alert and watch it arrive
Proving that alerting works means sending an alert, not reading configuration. Stop Node Exporter. Prometheus's next scrape fails, up{job="node"} becomes 0, the rule goes to pending and, after the one-minute for, to firing:
sudo systemctl stop node_exporterWatch the rule state through Grafana's Prometheus-style rules API, and wait for the receiver to log the page. It takes about two minutes: up to 15 seconds for the failed scrape, the 30-second evaluation interval, the one-minute pending period and the 10-second group_wait:
for i in $(seq 1 60); do
grep -q '^/page firing Node Exporter down' ~/grafana-alerts-demo/receiver.log && break
sleep 5
done
gapi http://127.0.0.1:3000/api/prometheus/grafana/api/v1/rules | jq -r '.data.groups[].rules[] | "\(.name): \(.state)"'
cat ~/grafana-alerts-demo/receiver.logCheck it worked
The rules list shows Node Exporter down: firing and Error log lines in demo-app: inactive. The receiver log gains a line like:
/page firing Node Exporter down page - Node Exporter on 127.0.0.1:9100 is not answering scrapesThat one line proves the whole chain: the Prometheus query, the threshold, the severity label routed by the policy to ops-pager, the URL in the contact point, and the token read from /etc/grafana/webhook_token, because the receiver rejects anything else. If you see rejected: missing or wrong token instead, the file holds a different token from the one the receiver was started with.
Now start Node Exporter again and wait for the resolved message, which arrives at the next group_interval after the rule returns to normal:
sudo systemctl start node_exporterfor i in $(seq 1 60); do
grep -q '^/page resolved Node Exporter down' ~/grafana-alerts-demo/receiver.log && break
sleep 5
done
tail -n 2 ~/grafana-alerts-demo/receiver.logThe last line starts /page resolved Node Exporter down, within about two minutes.
In the browser, the contact point page has a Test button that sends a sample notification. It is handy, but the stopped-exporter test above is stronger: it exercises the rule and the policy, not only the contact point.
Step 8 · Export existing alerts to files
Most Grafanas already have alerts that someone built in the browser. You do not have to retype them. The provisioning API exports rules, contact points and the policy tree in the same YAML format that the files use:
mkdir -p ~/grafana-alerts-demo/export
cd ~/grafana-alerts-demo/export
gapi -f 'http://127.0.0.1:3000/api/v1/provisioning/alert-rules/export?format=yaml' > alert-rules.yaml
gapi -f 'http://127.0.0.1:3000/api/v1/provisioning/contact-points/export?format=yaml' > contact-points.yaml
gapi -f 'http://127.0.0.1:3000/api/v1/provisioning/policies/export?format=yaml' > policies.yaml
grep -E '^ *(name|folder|title):' alert-rules.yaml
grep -E 'authorization_credentials' contact-points.yamlTo move a browser-made rule into code:
- Find it in
alert-rules.yaml(each group carries itsfolder,intervaland rules with theiruid), and copy that group into a file under/etc/grafana/provisioning/alerting/. - Keep the exported
uid. Grafana then updates the existing rule in place and marks it as provisioned, instead of creating a duplicate. - Read the exported model before you commit it. The browser stores extra fields (
intervalMs,maxDataPoints,editorMode) that are harmless but noisy; delete what you do not need and keeprefId,exprand the expression settings. - Run the alerting reload and check the rule's
provenanceis nowfile.
Contact points need one more change. The export hides secrets by default, so authorization_credentials (and other fields Grafana treats as secret, such as passwords, API keys and Slack webhook URLs) come out as a placeholder. Never commit a decrypted export (decrypt=true puts the real secrets in the file). Put each secret in its own private file, as you did with the token, and replace the placeholder with $__file{...}.
Check it worked
The first grep lists the server-health group, folder: Platform alerts and both rule titles. The second shows the credential lines with a placeholder, not the token. Confirm the token is nowhere in the export:
grep -c "$WH_TOKEN" ~/grafana-alerts-demo/export/*.yaml || trueEach file reports 0.
Step 9 · Remove the alerting setup
Deleting a provisioning file does not delete what it created: Grafana only adds and updates from files. To remove objects, you write a file that says so, load it, then delete it. This removes the two rules, the two contact points and resets the policy tree to Grafana's default (everything to the built-in email contact point). Read it before you load it, because resetPolicies also discards any routes added since:
sudo rm /etc/grafana/provisioning/alerting/rules.yaml /etc/grafana/provisioning/alerting/contact-points.yaml /etc/grafana/provisioning/alerting/policies.yaml
sudo tee /etc/grafana/provisioning/alerting/remove-demo.yaml > /dev/null <<'YAML'
apiVersion: 1
resetPolicies:
- 1
deleteRules:
- orgId: 1
uid: node-exporter-down
- orgId: 1
uid: demo-app-error-logs
deleteContactPoints:
- orgId: 1
uid: ops-pager-webhook
- orgId: 1
uid: ops-tickets-webhook
YAML
gapi --fail-with-body -X POST http://127.0.0.1:3000/api/admin/provisioning/alerting/reload
echo
sudo rm /etc/grafana/provisioning/alerting/remove-demo.yamlGrafana resets the policy before it deletes contact points, so the order inside the file does not matter. Then stop the receiver and remove the token and the demo folder:
pkill -f grafana-alerts-demo/receiver.py
sudo rm /etc/grafana/webhook_token
rm -rf ~/grafana-alerts-demoThe empty Platform alerts folder stays behind, because removal files cover rules and contact points, not folders. Delete it through the folder API: look up its uid by title, then delete it by uid:
FOLDER_UID="$(gapi http://127.0.0.1:3000/api/folders | jq -r '.[] | select(.title == "Platform alerts") | .uid')"
gapi --fail-with-body -X DELETE "http://127.0.0.1:3000/api/folders/$FOLDER_UID"
echoThe data source files stay: the dashboard tutorial uses the Prometheus data source, and the Loki data source is still useful for reading logs in Explore.
Check it worked
gapi http://127.0.0.1:3000/api/v1/provisioning/alert-rules | jq length
gapi http://127.0.0.1:3000/api/v1/provisioning/contact-points | jq -r '.[].name'
gapi http://127.0.0.1:3000/api/v1/provisioning/policies | jq -r .receiver
gapi http://127.0.0.1:3000/api/folders | jq -r '.[].title'The rule count is 0 (if this Grafana had no other rules), ops-pager and ops-tickets are gone from the contact points, the policy's receiver is the default email contact point again, and Platform alerts is no longer among the folders.
Next steps
- Decide which of your alerts deserve a page at all: write alerts that page only when users are hurt.
- Compare Grafana-managed rules with Prometheus rules and Alertmanager: send alerts with Prometheus Alertmanager.
- Write better log queries for log-based rules: search and count logs with LogQL.
- Revisit the dashboard files these data sources serve: build your first Grafana dashboard.
Related tutorials
- How to Build Your First Grafana Dashboard from Prometheus DataYou will install Grafana 13.3 from its apt repository on Ubuntu 26.04, set the admin password before the first start, keep it on localhost, connect it to Prometheus, and build a server overview dashboard with uptime, memory and CPU panels that lives in a file you can keep in Git.
- Write alerts that page only when users are hurtYou will have a tested set of Prometheus alert rules that page for user-facing symptoms, open tickets for causes, ride out flapping, route by severity in Alertmanager, mute knock-on alerts with inhibition and link each alert to a one-page runbook.
- How to Send Alerts with Prometheus AlertmanagerYou will write alert rules in Prometheus 3.16, test them with promtool, install Alertmanager 0.35 on Ubuntu 26.04 listening on localhost only, route alerts to a receiver, trigger and resolve a real alert by stopping Node Exporter, and learn silences and an email receiver whose password stays in a file.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials