I have the following python code:
import requests
import json
import time
# Grafana API configuration
GRAFANA_API_URL = 'https://grafana/api/v1/provisioning/alert-rules'
GRAFANA_API_TOKEN = 'xXx'
# Headers for the API request
headers = {
'Authorization': f'Bearer {GRAFANA_API_TOKEN}',
'Content-Type': 'application/json'
}
def get_alert_rules():
# Send GET request to the Grafana API to retrieve all alert rules
response = requests.get(GRAFANA_API_URL, headers=headers)
jdata = response.json()
data_out = []
contact_match = False
team_match = False
omgeving_match = False
for label in jdata:
try:
labeldata = label["labels"]
if labeldata['contact'] == 'AppFamily':
contact_match = True
if labeldata['team'] == 'IT':
team_match = True
if labeldata['env'] == 'prd':
env_match = True
if contact_match and team_match and env_match:
data_out.append(label)
except:
pass
with open("found_IT_alert.json", "w") as foundalerts_file:
json.dump(data_out, foundalerts_file, indent=4, sort_keys=True)
return data_out
if response.status_code != 200:
raise Exception(f"Failed to retrieve alert rules: {response.status_code} {response.text}")
def create_report(c_dict):
for dict_item in c_dict:
for key in dict_item:
if key == "id":
print(f"nID: {dict_item.get('id')}")
print(f"Title: {dict_item.get('title')}")
print(f"Data: {dict_item.get('data')}")
print(f"Data is type: {type(dict_item.get('data'))}")
def main():
# Retrieve all alert rules
alert_rules = get_alert_rules()
create_report(alert_rules)
if __name__ == "__main__":
main()
I end up with an output similair to this:
ID: 3979
Title: Env: AppFamily PROD | Metric: Swap Memory Usage | Threshold >80% | Interval: 1min | Pending: 2min | Notification: teams/email
Data: [{'refId': 'A', 'queryType': '', 'relativeTimeRange': {'from': 60, 'to': 0}, 'datasourceUid': '000000001', 'model': {'editorMode': 'code', 'expr': '(1- mem_swap_free{env="prd", application=~"AllKindsofApps"} / mem_swap_total{env="prd", application=~"AllKindsofApps"})*100', 'instant': True, 'intervalMs': 1000, 'legendFormat': '__auto', 'maxDataPoints': 43200, 'range': False, 'refId': 'A'}}, {'refId': 'C', 'queryType': '', 'relativeTimeRange': {'from': 60, 'to': 0}, 'datasourceUid': '__expr__', 'model': {'conditions': [{'evaluator': {'params': [80], 'type': 'gt'}, 'operator': {'type': 'and'}, 'query': {'params': ['C']}, 'reducer': {'params': [], 'type': 'last'}, 'type': 'query'}], 'datasource': {'type': '__expr__', 'uid': '__expr__'}, 'expression': 'A', 'intervalMs': 1000, 'maxDataPoints': 43200, 'refId': 'C', 'type': 'threshold'}}]
Data is type: <class 'list'>
I want to be able to extract expr from the data which is a python list, so in this case i would like to have as output:
expr: '(1- mem_swap_free{env="prd", application=~"AllKindsofApps"} / mem_swap_total{env="prd", application=~"AllKindsofApps"})*100'
and
'model': {'conditions': [{'evaluator': {'params': [80], 'type': 'gt'}, 'operator': {'type': 'and'}, 'query': {'params': ['C']}
I have tried the following to get the requested data:
— convert the list to dict
— convert the list to string and the try json.loads
— trying to build a dict by going over the list
— a lot of other ways trying to get some reasonable output
I want to understand with some help how to get the requested data available
Thank you in advance
1