使用 Python 进行 KQL 查询的 Azure 警报

问题描述 投票:0回答:1

我无法使用 Python 代码创建警报,需要手动创建它

以下是代码:

from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.monitor import MonitorManagementClient
from azure.mgmt.monitor.v2018_04_16.models import LogSearchRuleResource, Source, Schedule, Action


# Define the KQL query
kql_query = """
ConfigurationData
| where Computer contains "test_machine"
| where SvcName contains "test-service"
| where SvcState != "Running"
"""
# Azure subscription ID
subscription_id = '5xxxxxxxxxxxx'

# Resource group
resource_group_name = 'rg-name'

uri = "/subscriptions/xxxxxxxxx/resourceGroups/rg-anme/providers/Microsoft.Compute/virtualMachines/test-machine"

# Define parameters
scheduledqueryrules_custom_query_name = 'custom_query'
# Authenticate to Azure
credential = DefaultAzureCredential()

# Initialize Resource Management Client
resource_client = ResourceManagementClient(credential, subscription_id)
actions =  Action(
    odata_type="LogToMetricAction"
)
# Initialize Monitor Management Client
monitor_client = MonitorManagementClient(credential, subscription_id)
source = Source(query=kql_query, data_source_id=uri)
schedule = Schedule(frequency_in_minutes=5, time_window_in_minutes=15)
log_search = LogSearchRuleResource(location="northcentralus", source=source, action=actions)


rule_name = scheduledqueryrules_custom_query_name
rule_result = monitor_client.scheduled_query_rules.create_or_update(resource_group_name=resource_group_name, parameters=log_search,  rule_name="ddfed")

print("Rule created successfully:", rule_result)

错误:

ile "/usr/local/lib/python3.11/site-packages/azure/mgmt/monitor/v2018_04_16/operations/_scheduled_query_rules_operations.py", line 386, in create_or_update
    raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
azure.core.exceptions.HttpResponseError: (BadRequest) Invalid value  for properties.action.odata.type Activity ID: 49321a7c-b696-4042-aa5c-a109997224e4.
Code: BadRequest
Message: Invalid value  for properties.action.odata.type Activity ID: 49321a7c-b696-4042-aa5c-a1sddfrre4.

以下是 Microsoft Azure 类文档:

https://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2018_04_16.models.logsearchruleresource?view=azure-python

不确定出了什么问题,非常感谢任何帮助

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
azure-mgmt-resource==23.0.1
azure-monitor-query==1.3.0
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
python azure azure-media-services azure-monitoring azure-alerts
1个回答
0
投票

您收到错误是因为您使用了错误的

odata.type
值。

这对我有用。

test.py
:

from azure.mgmt.monitor import MonitorManagementClient
from azure.identity import DefaultAzureCredential


credentials = DefaultAzureCredential()
sub_id= "xxxxxxxxxxxxxxx"
resource_group = "xxxxxxxxxxxxxxx"
client = MonitorManagementClient(credential=credentials,subscription_id=sub_id)

rule_name = "kql_alert"
rule_result = client.scheduled_query_rules.create_or_update(resource_group,rule_name,{
          "location": "eastus",
          "description": "this is description for kql_alert",
          "enabled": "true",
          "provisioning_state": "Succeeded",
          "source": {
            "query": "Heartbeat | summarize AggregatedValue = count() by bin(TimeGenerated, 5m)",
            "data_source_id": f"/subscriptions/{sub_id}/resourceGroups/{resource_group}/providers/Microsoft.Compute/virtualMachines/AlertVM",
            "query_type": "ResultCount"
          },
          "schedule": {
            "frequency_in_minutes": "15",
            "time_window_in_minutes": "15"
          },
          "action": {
            "odata.type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction",
            "severity": "1",
            "azns_action": {},
            "trigger": {
              "threshold_operator": "GreaterThan",
              "threshold": "3",
              "metric_trigger": {
                "threshold_operator": "GreaterThan",
                "threshold": "5",
                "metric_trigger_type": "Consecutive",
                "metric_column": "Computer"
              }
            }
          }
        }
    )
print("Alert created Successfully.")

OUTPUT

作为参考,请检查此文档

© www.soinside.com 2019 - 2024. All rights reserved.