NGalert / Grafana 8 alert feature: How to export / import alerts as yml/json?

Inspired by @andi20002000 we came out with a bit more automated solution.

Makefile

check-grafana-token:
ifndef GRAFANA_TOKEN
	$(error GRAFANA_TOKEN is required)
endif

download-grafana-alerts: check-grafana-token
	curl -X GET \
		  -H "Authorization: Bearer ${GRAFANA_TOKEN}" \
	     'https://example.com/api/ruler/grafana/api/v1/rules' \
	     | jq > './grafana/alerts/alerts.json'

upload-grafana-alerts: check-grafana-token
	./upload-grafana-alerts.sh

upload-grafana-alerts.sh

#!/bin/sh

ALERTS_JSON_PATH=./grafana/alerts/alerts.json
NUMBER_OF_ALERTS=$(jq -c '.["folder-name"] | length' ${ALERTS_JSON_PATH})

for ((i=0; i<NUMBER_OF_ALERTS; i++)); do
  ALERT_OBJECT=$(jq -c --arg i "$i" '.["folder-name"][($i | tonumber)] | del(.rules[0].grafana_alert.uid)' ${ALERTS_JSON_PATH})
  ALERT_NAME=$(jq -c --arg i "$i" '.["folder-name"][($i | tonumber)].name' ${ALERTS_JSON_PATH})
  echo "Creating ${ALERT_NAME}...\n"
	curl -X POST \
		-H "Authorization: Bearer ${GRAFANA_TOKEN}" \
		-H "Content-type: application/json" \
		'https://example.com/api/ruler/grafana/api/v1/rules/folder-name' \
		-d "${ALERT_OBJECT}"
	echo "\n"
done
3 Likes