• Hi , I am unable to create multiple alerts withi...
# getting-started
a
> • Hi , I am unable to create multiple alerts within the same rule group for Grafana . The previous alerts created by pulumi are cached somehow and deleted when I rerun the code . The code is expected to create multiple alerts withing same folder and same rule group with a different alert name if ran from jenkins .
import * as pulumi from "@pulumi/pulumi";
import * as request from "request";
import * as grafana from "@lbrlabs/pulumi-grafana";
// Define a function to query Grafana for alert rules
async function getGrafanaAlertRules(apiUrl: string, apiKey: string): Promise<any[]> {
const options = {
`uri:
${apiUrl}/api/v1/provisioning/alert-rules
,`
headers: {
`"Authorization":
Bearer ${apiKey}
,
Copy code
},`
json: true,
};
return new Promise<any[]>((resolve, reject) => {
request.get(options, (error, response, body) => {
if (error) {
reject(error);
} else if (response.statusCode !== 200) {
`reject(
Request failed with status code ${response.statusCode}
);`
} else {
resolve(body);
}
});
});
}
// Define a function to create a new Grafana alert rule
async function createGrafanaAlertRule(folderUid: string, ruleGroup: string, title: string, existingRules: any) {
const newRule = {
name: title,
for: folderConfig.rules[0].for,
condition: folderConfig.rules[0].condition,
noDataState: folderConfig.rules[0].noDataState,
execErrState: folderConfig.rules[0].execErrState,
annotations: {},
labels: {},
isPaused: folderConfig.rules[0].isPaused,
datas: folderConfig.rules[0].data.map((data, index) => ({
refId: data.refId,
queryType: "",
relativeTimeRange: data.relativeTimeRange,
datasourceUid: data.datasourceUid,
model: JSON.stringify(data.model),
})),
}
if (existingRules !== null && existingRules !== undefined) {
console.log("*************************");
existingRules.push(newRule);
} else {
console.log("^^^^^^^^^^^^^^^^^^^^^^^^^^");
existingRules = [newRule];
}
const myAlertRule = new grafana.RuleGroup(ruleGroup, {
folderUid: folderUid,
intervalSeconds: 300, // "5m" in seconds
orgId: folderConfig.orgId.toString(),
rules: existingRules
});
console.log("Execure createGrafanaAlertRule, Expected resualt is: ", title)
}
async function updateGrafanaAlertRule(folderUid: string, ruleGroup: string, title: string) {
const myAlertRule = new grafana.RuleGroup(ruleGroup, {
folderUid: folderUid,
intervalSeconds: 300, // "5m" in seconds
orgId: folderConfig.orgId.toString(),
rules: folderConfig.rules.map((rule) => ({
name: title,
for: rule.for,
condition: rule.condition,
noDataState: rule.noDataState,
execErrState: rule.execErrState,
annotations: {},
labels: {},
isPaused: rule.isPaused,
datas: rule.data.map((data, index) => ({
refId: data.refId,
queryType: "",
relativeTimeRange: data.relativeTimeRange,
datasourceUid: data.datasourceUid,
model: JSON.stringify(data.model),
})),
})),
});
console.log("Execure updateGrafanaAlertRule, Expected resualt is: ", title)
}
const grafanaApiKey = " password";
const grafanaApiUrl = "<https://cyberark.grafana.net>";
// Get Grafana alert rules using the function
const grafanaAlertRulesPromise = getGrafanaAlertRules(grafanaApiUrl, grafanaApiKey);
grafanaAlertRulesPromise
.then((alertRules) => {
// console.log(process.env.PULUMI_STACK)
const folderUid = "AKIyIE-Vk"
const ruleGroup = "testrulegroup //uniq name based on rule set
const expectedTitle = "testalertname";
const updateIsTrue = false;
// You can also log the entire response if needed:
// console.log(JSON.stringify(alertRules, null, 2));
const ruleWithTitle = alertRules.find((rule) => rule.title.toUpperCase() === expectedTitle.toUpperCase());
if (ruleWithTitle === true) {
`console.log(
Alert rule with title "${expectedTitle}" found.
);` `console.log(
User request to update exist rule with title "${expectedTitle}"
);`
// Use to find the index value that matches in insted of for loop.
const ruleIndex = alertRules.findIndex((rule) => rule.title.toUpperCase() === expectedTitle.toUpperCase());
updateGrafanaAlertRule(alertRules[ruleIndex].folderUID, alertRules[ruleIndex].ruleGroup, alertRules[ruleIndex].title)
.then(() => {
`console.log(
Alert rule with title "${expectedTitle}" updated successfully.
);`
})
.catch((error) => {
`console.error(
Error creating a update alert rule: ${error}
);`
});
} else {
`console.error(
Alert rule with title "${expectedTitle}" not found.
);`
// If folderUid is exist, Find extract ruleGroup to avoide overridden
const ruleGroupIndex = alertRules.findIndex((rule) => rule.folderUid === folderUid);
if (ruleGroupIndex > -1) {
ruleGroup == alertRules[ruleGroupIndex].ruleGroup
}
// Create a new alert rule
createGrafanaAlertRule(folderUid, ruleGroup, expectedTitle, alertRules[ruleGroupIndex])
.then(() => {
`console.log(
New alert rule with title "${expectedTitle}" created successfully.
);`
})
.catch((error) => {
`console.error(
Error creating a new alert rule: ${error}
);`
});
}
})
.catch((error) => {
console.error("Error fetching Grafana alert rules:", error);
});
const folderConfig = {
//rule
};