Azure alerting for KQL query using Python

  Kiến thức lập trình

I could not able to create alert using Python code, Manually It got created

Below is the code:

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)

Error:

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.

Below is the Microsoft Azure docs for classes:

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

Not sure what went wrong and any help be greatly appreciated

Python Version: 3.11
Packages:

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

LEAVE A COMMENT