我想使用Python(通过Azure函数)从Azure Monitor获取特定警报。Azure Monitor将为每个事件触发az函数。
目前我使用的是来自azure.mgmt.alertsmanagement.operations模块的get_all,这允许我获取所有警报。也已经测试了get_by_id,但我不得不指定alert_id,而我希望自动获取它。
import logging
import urllib3
import os
import json
import requests
from azure.identity import ClientSecretCredential
from azure.mgmt.alertsmanagement import AlertsManagementClient
subscription_id =""
client_id =""
client_secret =""
tenant_id = ""
credential = ClientSecretCredential(
tenant_id=tenant_id,
client_id=client_id,
client_secret=client_secret
)
print("===Auth Azure Monitor===")
client = AlertsManagementClient(
credential,
subscription_id
)
print("=== Get alert event from Az Monitor & Post it to monitoring platform === ")
headers = {'Authorization': f'authtoken {token}'}
for alert in client.alerts.get_all():
if alert.name == "alert_rule_name" :
attributes = {'CLASS': 'EVENT',
'severity': 'CRITICAL',
'msg': alert.name,
'lastModifiedDateTime': json.dumps(alert.properties.essentials.last_modified_date_time, indent=4, sort_keys=True, default=str)
}
payload = [{'eventSourceHostName': alert.properties.essentials.target_resource_name, 'attributes': attributes}]
print("JSON_PAYLOAD :", payload)
## Some code here to push the Alert to a monitoring platform ..
请在下面找到Azure Monitor使用get_all发送的json:
{'value': [{'properties': {'essentials': {
'severity': 'Sev2',
'signalType': 'Metric',
'alertState': 'New',
'monitorCondition': 'Fired',
'monitorService': 'Platform',
'targetResource': '/subscriptions/sub_id/resourcegroups/rsg_name/providers/microsoft.compute/virtualmachines/vm_name',
'targetResourceName': 'vm_name',
'targetResourceGroup': 'rsg_name',
'targetResourceType': 'virtualmachines',
'sourceCreatedId': '5f33r_rsg_name_microsoft.insights_metricAlerts_alert_rule_name-1899618006',
'alertRule': '/subscriptions/sub_id/resourceGroups/rsg_name/providers/microsoft.insights/metricAlerts/alert_rule_name',
'startDateTime': '2023-05-09T13:32:28.1880147Z',
'lastModifiedDateTime': '2023-05-09T13:32:28.1880147Z',
'lastModifiedUserName': 'System',
'actionStatus': {'isSuppressed': False}, 'description': ''}
},
'id': '/subscriptions/sub_id/providers/Microsoft.AlertsManagement/alerts/2222-5555-88888',
'type': 'Microsoft.AlertsManagement/alerts',
'name': 'alert_rule_name'},
如您所见,我正在通过[if www.example.com =="alert_rule_name"]进行过滤,但这不是我要查找的内容(我得到了一个事件列表)。alert.name == "alert_rule_name"] and this is not what I'm looking for (I got a list of Events).
当Azure Monitor调用我的函数时,是否有方法从有效负载中获取警报ID?这是为了使用此ID获取特定警报(事件)。
先谢谢你了
2条答案
按热度按时间wbrvyc0a1#
是否有方法在Azure Monitor
您可以使用下面的代码使用python获取带有payload的Alert id。
您需要在属性中添加**
alert.id
**,以获取您的特定警报的警报ID。代码:
输出:
kmbjn2e32#
Azure Monitor触发下面的Azure函数,该函数仅解析一个事件并将其转发到另一个目标,以便通知支持团队: