Arpit Kathuria
Arpit Kathuria

Reputation: 414

Get all active alerts of a subscription in Azure Monitor using Python

I just needed to get all active alerts from Azure monitor for all resources in a subscription using Python.
For the same purpose, rest API is available, check this.
I have checked this, but it provides the alert / metric definitions and not the alert itself.
Is some thing similar available using Azure python SDK?
Would be helpful if anyone can provide some insights. Thanks in advance.

Upvotes: 1

Views: 967

Answers (1)

unknown
unknown

Reputation: 7483

This is the function that doc provides. But it returns this: enter image description here

It seems not used for the new version.

get_all is used to list all existing alerts. It returns a paging container for iterating over a list of Alert object.

Install package: pip install azure-mgmt-alertsmanagement

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.alertsmanagement import AlertsManagementClient
 
subscription_id = 'subscription_id '
tenant_id = 'tenant_id '
client_id = 'client_id '
client_secret = 'client_secret'
 
credentials = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
 
client = AlertsManagementClient(
    credentials,
    subscription_id
)
 
for alert in client.alerts.get_all():
    print((alert.name))

So, I tried to call the REST API with Python. It works.

import requests
import json

client_id = ''
client_secret = ''
subscription_id = ''
tenant_id = ''

# authorize with azure
url = "https://login.microsoftonline.com/" + tenant_id + "/oauth2/v2.0/token"
data = "scope=https%3A%2F%2Fmanagement.azure.com%2F.default&client_id=" + client_id + "&grant_type=client_credentials&client_secret=" + client_secret
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post(url, data=data, headers=headers)

# create new resource group using Azure REST API
# https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts?api-version=2018-05-05
url = "https://management.azure.com/subscriptions/" + subscription_id + "/providers/Microsoft.AlertsManagement/alerts?api-version=2018-05-05"
headers = { 'Authorization': 'Bearer ' + response.json()['access_token']}
response = requests.get(url, headers=headers)

print(response.json())

enter image description here

Upvotes: 2

Related Questions