Grafana 8: How to import/export alerts in unified alert section?

I want to promote rules created in lower environment to higher environments. I dont see any option to export and import the rules created in the new unified alert section. How can I do this?

Grafana 8 alerting has a an API that will allow you to create custom scripts, etc for managing rules across environments. Roughly, you would get the set of rules from one environment, map things like datasource UIDs across environments, and then put the rules into the other environment. Strong naming conventions would be essential in this case so that you have a clear way of identifying mappings between the different environments

1 Like

@davidparrott , could you point me to the api documentation? The one I found here Swagger Editor doesnt have a POST method to create alerts.

@joshiparth1000 you don’t create alerts, you create alerting rules that are evaluated. I don’t believe we intend to implement a mechanism for directly creating alert instances in this system.

Sorry, I actually meant alerting rules. I dont see an API endpoint to create them. There is one under /prometheus to GET them though.

1 Like

/api/ruler/{Recipient}/api/v1/rules/{Namespace} is the endpoint you’re looking for.

Thanks for pointing it out. What is the value of Namespace? I dont see it mentioned anywhere in the UI.

@joshiparth1000 Namespace corresponds to the grafana folder you would like the alerts to live in. It’s something of a compromise between the prometheus API structure and the way Grafana has managed alerts in the past.

It makes more sense in the UI, I think, when you’re doing rule creation. You name the rule, select grafana managed, and then select the folder you’re interested in using. That folder name is the same as the namespace portion of the URL

Could you give a full example on this as I can’t figure it out and can’t find the API docs for this.

Run this in the devtools console of a Grafana tab. I guess with minor modifications it could be adapted to run in nodejs, on schedule.

(async () => {
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    const aids = await fetch(`/api/alerts/`).then(v => v.json());
    let alerts = (await Promise.all(
        aids.map(({ id, dashboardSlug }) => sleep(Math.random() * 10000).then(() => fetch(`/api/alerts/${id}`))
            .then(v => v.json()).then(v => ({ dashboardSlug, response: v })))))
        .map((v) => ({ ...v, exprs: v.response.Settings.conditions.map(v => [v.operator.type, v.query.model.expr, v.evaluator.type, v.evaluator.params[0]]) }));
    const byBoardAgg = alerts.reduce((byBoard, a) => {
        byBoard[a.dashboardSlug] = [...(byBoard[a.dashboardSlug] || []), a.exprs];
        return byBoard;
    }, {})
    console.log(byBoardAgg)
}
)();

how configure my grafana instance on boot with my alerts …