Azure-sdk-for-net: [Question] How to create a dynamic alert rule ?

Created on 10 Jun 2020  ·  9Comments  ·  Source: Azure/azure-sdk-for-net

Hi guys, I need to create a Dynamic Threshold Alert Rule for my Application Insisghts instance. Recently I was creating a static rule:

var api = Azure.Configure()
               .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
               .Authenticate(credentials)
               .WithSubscription(subscriptionId);

await api.AlertRules
         .MetricAlerts
         .Define("Test rule")
         .WithExistingResourceGroup(resourceGroup)       
         .WithTargetResource(appInsightsId)
         .WithPeriod(new TimeSpan(0, 5, 0)) //Aggregation granularity (Period)
         .WithFrequency(new TimeSpan(0, 5, 0)) //Frequency of evaluation
         .WithAlertDetails(2, "test desc")
         .WithActionGroups(id)
         .DefineAlertCriteria("condition name")
         .WithMetricName("metric name")
         .WithCondition(MetricAlertRuleTimeAggregation.Count, MetricAlertRuleCondition.GreaterThanOrEqual, 1)
         .Attach()
         .CreateAsync()

but now I need to create a dynamic rule - looking at the json payload for creating a Dynamic Alert Rule for Single Resource https://docs.microsoft.com/pl-pl/rest/api/monitor/metricalerts/createorupdate#create-or-update-a-dynamic-alert-rule-for-single-resource I can see the matching classes in the source code whose indicates the appropiate fields in that payload (e.g. DynamicMetricCriteria, DynamicThresholdFailingPeriods and so on), but they are not publicly available to be used in the SDK. Or am I wrong ?

To create a workaround, I use the IGenericResource to create that alert rule:

await _genericResources.Define(name)
                .WithRegion(region)
                .WithExistingResourceGroup(resourceGroup)
                .WithResourceType("metricAlerts")
                .WithProviderNamespace("microsoft.insights")
                .WithoutPlan()
                .WithApiVersion("2018-03-01")
                .WithParentResource("")
                .WithProperties(...)
                .CreateAsync();

but that approach does not provide the way to set the required location field, and I end up with the error message:The provided location 'WestEurope' is not available for resource type 'microsoft.insights/metricalerts'. List of available regions for the resource type is 'global'.

So, any ideas how to deal with it ? It does no matter for me whether I use the Fluent API or the IGenericResource interface.

Environment:

  • Microsoft.Azure.Management.Fluent v1.32.0
  • Microsoft.Azure.Management.ResourceManager.Fluen v1.32.0
Mgmt Monitor - Alerts Service Attention customer-reported needs-team-attention question

All 9 comments

Thanks for the feedback! We are routing this to the appropriate team for follow-up. cc @AzmonAlerts.

Hi @tony6636, thanks for reaching out.
When using the IGenericResource interface, can you please try specifying "global" for the region variable: .WithRegion("global")

This should resolve the region issue you're facing.
We will also look into exposing dynamic threshold-related properties in the Fluent API.

@harelbr thanks for the reply. I tried the approach you suggest, but without success.

In Azure Web App, I can see that the API version 2018-03-01 is being used when a new dynamic metric alert is created. Here's my properties payload (I'm using the same API version and the WithRegion("global") method)

{
"description": "",
"enabled": true,
"severity": 2,
"windowSize": "PT30M",
"evaluationFrequency": "PT5M",
"scopes": [
    "/subscriptions/<id>/resourceGroups/<group>/providers/microsoft.insights/components/<app insights instance>"
],
"criteria": {
    "allOf": [
        {
            "metricName": "exceptions/server",
            "metricNamespace": "microsoft.insights/components",
            "Operator": "GreaterOrLessThan",
            "timeAggregation": "Count",
            "name": "Metric1",
            "dimensions": [],
            "monitorTemplateType": "13",
            "criterionType": "DynamicThresholdCriterion",
            "alertSensitivity": "High",
            "failingPeriods": {
                "numberOfEvaluationPeriods": 4,
                "minFailingPeriodsToAlert": 4
            },
            "ignoreDataBefore": null
        }
    ],
    "odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria"
},
"actions": [
    {
        "actionGroupId": "/subscriptions/<id>/resourceGroups/<group>/providers/microsoft.insights/actionGroups/<action group>",
        "webhookProperties": {}
    }
],
"autoMitigate": true,
"targetResourceType": "microsoft.insights/components",
"targetResourceRegion": "westeurope"
}

and I receive the following error
No registered resource provider found for location 'global' and API version '2018-03-01' for type 'components'. The supported api-versions are '2014-04-01, 2014-08-01, 2014-12-01-preview, 2015-05-01, 2018-05-01-preview, 2020-02-02-preview'. The supported locations are ', eastus, southcentralus, northeurope, westeurope, southeastasia, westus2, uksouth, canadacentral, centralindia, japaneast, australiaeast, koreacentral, francecentral, centralus, eastus2, eastasia, westus, southafricanorth, northcentralus, brazilsouth, switzerlandnorth, australiasoutheast'.

so then I switch to

.WithApiVersion("2018-05-01-preview")

which ends with that error message
I get this error The subscription is not registered for the resource type 'components' in the location 'global'. Please re-register for this provider in order to have access to this location.

Hi @tony6636 - The 'No registered resource provider...' error indicates the resource type being used is Microsoft.Insights/components, while it needs to be Microsoft.Insights/metricAlerts.

Can you please double check that the correct resource type is specified: .WithResourceType("metricAlerts")

If that's not the case, can you please share the full command you're trying to run?

Thanks!

Hi @harelbr, I used your suggestion to use .WithResourceType("metricAlerts"), and now I get the error:
Required property 'threshold' not found in JSON. Path '', line 13, position 9.

but that property is not being used in https://docs.microsoft.com/pl-pl/rest/api/monitor/metricalerts/createorupdate#create-or-update-a-dynamic-alert-rule-for-single-resource

the used query

await _genericResources.Define(name)
                .WithRegion("global")
                .WithExistingResourceGroup(resourceGroup)
                .WithResourceType("metricAlerts")
                .WithProviderNamespace("microsoft.insights")
                .WithoutPlan()
                .WithApiVersion("2018-03-01")
                .WithParentResource("")
                .WithProperties(...)
                .CreateAsync();

the payload for the .WithProperties(...) method:

{
    "description": "",
    "enabled": true,
    "severity": 2,
    "windowSize": "PT30M",
    "evaluationFrequency": "PT5M",
    "scopes": [
        "/subscriptions/<id>/resourceGroups/<group>/providers/microsoft.insights/components/<app insights instance>"
    ],
    "criteria": {
        "allOf": [
            {
                "metricName": "exceptions/server",
                "metricNamespace": "microsoft.insights/components",
                "Operator": "GreaterOrLessThan",
                "timeAggregation": "Count",
                "name": "Metric1",
                "dimensions": [],
                "monitorTemplateType": "13",
                "criterionType": "DynamicThresholdCriterion",
                "alertSensitivity": "High",
                "failingPeriods": {
                    "numberOfEvaluationPeriods": 4,
                    "minFailingPeriodsToAlert": 4
                },
                "ignoreDataBefore": null
            }
        ],
        "odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria"
    },
    "actions": [
        {
            "actionGroupId": "/subscriptions/<id>/resourceGroups/<group>/providers/microsoft.insights/actionGroups/<action group>",
            "webhookProperties": {}
        }
    ],
    "autoMitigate": true,
    "targetResourceType": "microsoft.insights/metricAlerts",
    "targetResourceRegion": "westeurope"
}

Hi @tony6636 - Can you please try changing the "targetResourceType" to the following:
"targetResourceType": "microsoft.insights/components"

hi @harelbr, I tried - that also gives me the error Required property 'threshold' not found in JSON. Path '', line 13, position 9.

Hi @tony6636, it seems like this is an issue with the way the payload is passed into the .WithProperties() method. This method expects an object as an input parameter.

Can you please try taking the same properties payload you've specified in your previous reply, and construct an object of it:

string s = “{<the payload properties>}”;
var payload = JObject.Parse(s);

And then pass that payload object to the WithProperties() method.

hi @harelbr thanks for the reply, now it works fine - thank you for the assistance!

Was this page helpful?
0 / 5 - 0 ratings