使用Python SDK创建Azure自定义KQL查询告警时遇缺失name属性错误
使用Python SDK创建基于KQL的Azure告警时触发BadRequest错误
我们尝试通过Python SDK创建基于自定义KQL查询的Azure告警,但执行代码时收到BadRequest错误,提示JSON中缺少必填属性'name',无法完成告警创建。
原代码
from azure.mgmt.monitor import MonitorManagementClient from azure.identity import DefaultAzureCredential credentials = DefaultAzureCredential() sub_id= "xxxx" resource_group = "rgname" client = MonitorManagementClient(credential=credentials,subscription_id=sub_id) # Define the KQL query kql_query = """ ServiceMonitor | where Computer contains "xyz-host" | where SvcName contains "linux-service" | where SvcState != "Running" """ # Create a unique name for the metric alert metric_alert_name = "KQL_Metric_alert" # Create the alert based on the KQL query Alert = client.metric_alerts.create_or_update(resource_group, metric_alert_name, # Use the unique metric alert name { "location": "global", "description": "Alert triggered when the service is not running on xyz_host", "severity": "3", "enabled": True, "scopes": [ f"/subscriptions/{sub_id}/resourceGroups/{resource_group}" ], "evaluation_frequency": "PT1M", "window_size": "PT15M", "target_resource_type": "Microsoft.Insights/components", "target_resource_region": "global", "criteria": { "odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria", "all_of": [ { "criterion_type": "StaticThresholdCriterion", "metric_name": "KQLQueryExecutionResult", "metric_namespace": "", "operator": "GreaterThan", "threshold": 0, "aggregation": "Count", "dimensions": [], "metric_namespace": "microsoft.insights/components", "additional_properties": { "query": kql_query } } ] }, "auto_mitigate": False, "actions": [ { "action_group_id": f"/subscriptions/{sub_id}/resourceGroups/rg-name/providers/microsoft.insights/actionGroups/AlertTrigger", "webhook_properties": {} } ] } ) print("Alert created Successfully.")
错误信息
Traceback (most recent call last): File "/Users/testuser/Documents/test/alerting/service_check.py", line 21, in <module> Alert = client.metric_alerts.create_or_update(resource_group, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/vcimalap/Documents/test/alerting/.venv/lib/python3.11/site-packages/azure/core/tracing/decorator.py", line 78, in wrapper_use_tracer return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/vcimalap/Documents/test/alerting/.venv/lib/python3.11/site-packages/azure/mgmt/monitor/v2018_03_01/operations/_metric_alerts_operations.py", line 609, in create_or_update raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) azure.core.exceptions.HttpResponseError: (BadRequest) Required property 'name' not found in JSON. Path '', line 1, position 512. Activity ID: df779cd2-198b-4098-be4f-c68d95c27f00. Code: BadRequest Message: Required property 'name' not found in JSON. Path '', line 1, position 512. Activity ID: df779cd2-198b-4098-be4f-c68d95c27f00.
环境信息
- Python版本:3.11
- 依赖包版本:
azure-common==1.1.28 azure-core==1.30.1 azure-identity==1.16.0 azure-mgmt-core==1.4.0 azure-mgmt-monitor==6.0.2 certifi==2024.2.2 cffi==1.16.0 charset-normalizer==3.3.2 cryptography==42.0.5 idna==3.7 isodate==0.6.1 msal==1.28.0 msal-extensions==1.1.0 packaging==24.0 portalocker==2.8.2 pycparser==2.22 PyJWT==2.8.0 requests==2.31.0 six==1.16.0 typing_extensions==4.11.0 urllib3==2.2.1
错误原因及修复方案
核心问题点
- 缺失准则名称:告警规则的
criteria.all_of数组内的每个准则对象必须包含name属性,这是Azure API的必填项。 - 错误的告警类型:你要创建的是日志查询(KQL)告警,而非指标告警,
criteria.odata.type应改为Microsoft.Azure.Monitor.LogQueryCriteria。 - 目标资源类型错误:针对Log Analytics工作区的查询,
target_resource_type应为Microsoft.OperationalInsights/workspaces,且scope需要指定具体工作区ID,而非资源组。 - 冗余属性:原代码重复定义了
metric_namespace,需移除冗余项。
修正后的完整代码
from azure.mgmt.monitor import MonitorManagementClient from azure.identity import DefaultAzureCredential credentials = DefaultAzureCredential() sub_id= "xxxx" resource_group = "rgname" # 替换为你的Log Analytics工作区ID workspace_id = f"/subscriptions/{sub_id}/resourceGroups/{resource_group}/providers/Microsoft.OperationalInsights/workspaces/your-workspace-name" client = MonitorManagementClient(credential=credentials,subscription_id=sub_id) # Define the KQL query kql_query = """ ServiceMonitor | where Computer contains "xyz-host" | where SvcName contains "linux-service" | where SvcState != "Running" """ # Create a unique name for the log alert alert_name = "KQL_Service_Down_Alert" # Create the alert based on the KQL query alert = client.metric_alerts.create_or_update( resource_group_name=resource_group, rule_name=alert_name, parameters={ "location": "global", "description": "Alert triggered when the service is not running on xyz_host", "severity": "3", "enabled": True, "scopes": [workspace_id], "evaluation_frequency": "PT1M", "window_size": "PT15M", "target_resource_type": "Microsoft.OperationalInsights/workspaces", "target_resource_region": "eastus", # 替换为你的工作区所在区域 "criteria": { "odata.type": "Microsoft.Azure.Monitor.LogQueryCriteria", "query": kql_query, "time_aggregation": "Count", "operator": "GreaterThan", "threshold": 0, "name": "ServiceDown_Criterion" }, "auto_mitigate": False, "actions": [ { "action_group_id": f"/subscriptions/{sub_id}/resourceGroups/rg-name/providers/microsoft.insights/actionGroups/AlertTrigger", "webhook_properties": {} } ] } ) print("Alert created Successfully.")
额外说明
- 替换代码中的
your-workspace-name为实际的Log Analytics工作区名称,eastus为工作区所在区域。 - 确保使用的
DefaultAzureCredential拥有Monitoring Contributor或更高权限,以创建告警规则。
内容的提问来源于stack exchange,提问作者GoneCase123
相关产品推荐
相关产品推荐

