【发布时间】:2020-12-16 01:47:11
【问题描述】:
我只需要使用 Python 从 Azure 监视器获取订阅中所有资源的所有活动警报。
出于同样的目的,可以使用 REST API,check this。
我检查了this,但它提供了警报/指标定义,而不是警报本身。
使用 Azure python SDK 是否可以使用类似的东西?
如果有人可以提供一些见解,将会很有帮助。提前致谢。
【问题讨论】:
我只需要使用 Python 从 Azure 监视器获取订阅中所有资源的所有活动警报。
出于同样的目的,可以使用 REST API,check this。
我检查了this,但它提供了警报/指标定义,而不是警报本身。
使用 Azure python SDK 是否可以使用类似的东西?
如果有人可以提供一些见解,将会很有帮助。提前致谢。
【问题讨论】:
新版好像没用过。
get_all 用于列出所有现有警报。它返回一个分页容器,用于迭代 Alert 对象的列表。
安装包: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))
所以,我尝试用 Python 调用 REST API。它有效。
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())
【讨论】: