I am trying to create Azure Alert using Python SDK and Below is the code
from azure.mgmt.monitor import MonitorManagementClient
from azure.mgmt.monitor.models import RuleMetricDataSource
from azure.identity import DefaultAzureCredential
from azure.mgmt.monitor.models import ThresholdRuleCondition
from azure.mgmt.monitor.models import RuleEmailAction
subscription_id = 'xxxxxx-xxxxxxxxxx-xxxxxxxxx'
resource_group_name = 'example-rg'
vm_name = 'example_vm'
# Set up the credentials
credentials = DefaultAzureCredential()
resource_id = (
"subscriptions/{}/"
"resourceGroups/{}/"
"providers/Microsoft.Compute/virtualMachines/{}"
).format(subscription_id, resource_group_name, vm_name)
# create client
client = MonitorManagementClient(
credentials,
subscription_id
)
# I need a subclass of "RuleDataSource"
data_source = RuleMetricDataSource(
resource_uri=resource_id,
metric_name='Percentage CPU'
)
# I need a subclasses of "RuleCondition"
rule_condition = ThresholdRuleCondition(
data_source=data_source,
operator='GreaterThanOrEqual',
threshold=90,
window_size='PT5M',
time_aggregation='Average'
)
# I need a subclass of "RuleAction"
rule_action = RuleEmailAction(
send_to_service_owners=True,
custom_emails=[
'abc@gmail.com'
]
)
rule_name = 'MyPyTestAlertRule'
my_alert = client.alert_rules.create_or_update(
resource_group_name,
rule_name,
{
'location': 'North Central US',
'alert_rule_resource_name': rule_name,
'description': 'Testing Alert rule creation',
'is_enabled': True,
'condition': rule_condition,
'actions': [
rule_action
]
}
)
Unfortunately I am getting below error, difficult find any valid example code in the website. It would be really great if somebody provides a example to create Azure alert using python SDK.
As per error it classic alert rules based on this metric is no longer supported.
Traceback (most recent call last):
File "/Users/testuser/test/alert/test.py", line 71, in <module>
my_alert = monitor_client.alert_rules.create_or_update(
File "/usr/local/lib/python3.10/site-packages/azure/core/tracing/decorator.py", line 78, in wrapper_use_tracer
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/azure/mgmt/monitor/v2016_03_01/operations/_alert_rules_operations.py", line 370, in create_or_update
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
azure.core.exceptions.HttpResponseError: (BadRequest) Creating or editing classic alert rules based on this metric is no longer supported. To learn about new alert rules see https://aka.ms/create-metric-alerts
Code: BadRequest
Message: Creating or editing classic alert rules based on this metric is no longer supported. To learn about new alert rules see https://aka.ms/create-metric-alerts
This worked for me.
I have used azure.mgmt.monitor
from package azure-mgmt-monitor
For Reference check this document.
app.py
:
from azure.mgmt.monitor import MonitorManagementClient
from azure.identity import DefaultAzureCredential
credentials = DefaultAzureCredential()
sub_id= "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
resource_group = "xxxxxxxxxxxxxxxxx"
client = MonitorManagementClient(credential=credentials,subscription_id=sub_id)
Alert = client.metric_alerts.create_or_update(resource_group,
"Metric_alert_",
{
"location": "global",
"description": "This is the description of the rule1",
"severity": "3",
"enabled": True,
"scopes": [
f"/subscriptions/{sub_id}/resourceGroups/{resource_group}/providers/Microsoft.Compute/virtualMachines/testvm"
],
"evaluation_frequency": "PT1M",
"window_size": "PT15M",
"target_resource_type": "Microsoft.Compute/virtualMachines",
"target_resource_region": "Australiaeast", #VM's region
"criteria": {
"odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria",
"all_of": [
{
"criterion_type": "DynamicThresholdCriterion",
"name": "High_CPU_80",
"metric_name": "Percentage CPU",
"metric_namespace": "microsoft.compute/virtualmachines",
"operator": "GreaterOrLessThan",
"time_aggregation": "Average",
"dimensions": [],
"alert_sensitivity": "Medium",
"failing_periods": {
"number_of_evaluation_periods": "4",
"min_failing_periods_to_alert": "4"
},
}
]
},
"auto_mitigate": False,
"actions": [
]
}
)
print("Alert created Successfully.")
OUTPUT
: