2

I want to create a Log Alert using PowerShell based on a query. I follow the instructions under https://learn.microsoft.com/en-us/azure/azure-monitor/platform/alerts-log#managing-log-alerts-using-powershell and I've adapted my code as below:

$source = New-AzScheduledQueryRuleSource -Query "AzureActivity | where Category == 'Policy' and Level != 'Informational' | extend p=todynamic(Properties) | extend policies=todynamic(tostring(p.policies)) | mvexpand policy = policies | where p.isComplianceCheck == 'False'" -DataSourceId "$Workspace.ResourceId"

$schedule = New-AzScheduledQueryRuleSchedule -FrequencyInMinutes 5 -TimeWindowInMinutes 5

$metricTrigger = New-AzScheduledQueryRuleLogMetricTrigger -ThresholdOperator "GreaterThan" -Threshold 0 -MetricTriggerType "Consecutive" -MetricColumn "_ResourceId"

$triggerCondition = New-AzScheduledQueryRuleTriggerCondition -ThresholdOperator "GreaterThan" -Threshold 0 -MetricTrigger $metricTrigger

$aznsActionGroup = New-AzScheduledQueryRuleAznsActionGroup -ActionGroup "$actionGroup.Id" -EmailSubject "New Resource Group with missing tags" -CustomWebhookPayload "{ `"alert`":`"#alertrulename`", `"IncludeSearchResults`":true }"

$alertingAction = New-AzScheduledQueryRuleAlertingAction -AznsAction $aznsActionGroup -Severity "3" -Trigger $triggerCondition

The above commands succeed but when I run the following one to create the rule:

New-AzScheduledQueryRule -ResourceGroupName $ResourceGroup -Location $Location -Action $alertingAction -Enabled $true -Description "Alert description" -Schedule $schedule -Source $source -Name "Alert Name"

I'm getting a BadRequest:

PS /home/nicolas> New-AzScheduledQueryRule -ResourceGroupName $ResourceGroup -Location $Location -Action $alertingAction -Enabled $true -Description "Alert description" -Schedule $schedule -Source$source -Name "Alert Name"
WARNING: 12:29:17 AM - *** The namespace for all the model classes will change from Microsoft.Azure.Management.Monitor.Management.Models to Microsoft.Azure.Management.Monitor.Models in future releases.
WARNING: 12:29:17 AM - *** The namespace for output classes will be uniform for all classes in future releases to make it independent of modifications in the model classes.
New-AzScheduledQueryRule: Exception type: Exception, Message: System.Exception: Error occurred while creating Log Alert rule
 ---> System.AggregateException: One or more errors occurred. (Operation returned an invalid status code 'BadRequest')
 ---> Microsoft.Azure.Management.Monitor.Models.ErrorResponseException: Operation returned an invalid status code 'BadRequest'
   at Microsoft.Azure.Management.Monitor.ScheduledQueryRulesOperations.CreateOrUpdateWithHttpMessagesAsync(String resourceGroupName, String ruleName, LogSearchRuleResource parameters, Dictionary`2customHeaders, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at Microsoft.Azure.Commands.Insights.ScheduledQueryRules.NewScheduledQueryRuleCommand.ProcessRecordInternal()
   --- End of inner exception stack trace ---
   at Microsoft.Azure.Commands.Insights.ScheduledQueryRules.NewScheduledQueryRuleCommand.ProcessRecordInternal()
   at Microsoft.Azure.Commands.Insights.MonitorCmdletBase.ExecuteCmdlet(), Code: Null, Status code:Null, Reason phrase: Null
PS /home/nicolas>

I can't find the cause.

Do you have any idea ?

Thanks in advance Nicolas

Nicolas
  • 23
  • 3
  • Nicolas, were you able to get this working? I'm having the same issue. – SmiffyKmc Sep 24 '20 at 13:11
  • Hi, no, I worked around the problem by using an ARM template for the alert deployment. – Nicolas Sep 24 '20 at 19:56
  • Was that just to deploy or create the alert :)? I'm investigating creating alerts for resources which I believed the original solution you were thinking of was doing. – SmiffyKmc Sep 25 '20 at 11:24

2 Answers2

2

The bad request error is too board, you could use Fiddler to catch the detailed error message. And specify value for $actionGroup.Id and $Workspace.ResourceId(workspace is you created before). I refer to this article and work well here is my code:

$source = New-AzScheduledQueryRuleSource -Query 'Heartbeat | summarize AggregatedValue = count() by bin(TimeGenerated, 5m), _ResourceId' -DataSourceId "/subscriptions/xxxxxxx/resourceGroups/xxxxxxx/providers/microsoft.OperationalInsights/workspaces/yourWorkspaceName"

$schedule = New-AzScheduledQueryRuleSchedule -FrequencyInMinutes 15 -TimeWindowInMinutes 30

$metricTrigger = New-AzScheduledQueryRuleLogMetricTrigger -ThresholdOperator "GreaterThan" -Threshold 2 -MetricTriggerType "Consecutive" -MetricColumn "_ResourceId"

$triggerCondition = New-AzScheduledQueryRuleTriggerCondition -ThresholdOperator "LessThan" -Threshold 5 -MetricTrigger $metricTrigger

$aznsActionGroup = New-AzScheduledQueryRuleAznsActionGroup -ActionGroup "/subscriptions/xxxxxxx/resourceGroups/xxxxxxx/providers/microsoft.insights/actiongroups/yourAGName" -EmailSubject "Custom email subject" -CustomWebhookPayload "{ `"alert`":`"#alertrulename`", `"IncludeSearchResults`":true }"

$alertingAction = New-AzScheduledQueryRuleAlertingAction -AznsAction $aznsActionGroup -Severity "3" -Trigger $triggerCondition


New-AzScheduledQueryRule -ResourceGroupName "xxxxxxx" -Location "Central US" -Action $alertingAction -Enabled $true -Description "Alert description" -Schedule $schedule -Source $source -Name "Alert Name"

Here is output:

enter image description here

Joey Cai
  • 18,968
  • 1
  • 20
  • 30
  • Thanks for your input. I know that the BadRequests are too board but your suggestion about Fiddler is very helpful because I didn't know it. As for this issue, on Monday Sunday I decided to workaround the problem by using an ARM template for the alert deployment and it works. Anyway, I will keep your recommendation for a future use. – Nicolas Mar 31 '20 at 06:50
  • Hey there, I'm actually working on this myself now and getting the same issue. Bit oblivious as to what to do. Am I supposed to create the Alert first in Azure? I believed you can create one from scratch using the Powershell? – SmiffyKmc Sep 23 '20 at 13:12
0

Your failure is in the first line.

"$Workspace.ResourceId" results to: ".ResourceId"

You need to write it the following way:

"$($Workspace.ResourceId)" results to: "TheResourceIdOfWorkspace"

Or just leaf away the quotation marks.

AlyaKoni
  • 1
  • 1