I am going nuts here. How in the world can I create a new alert rule in Azure using PowerShell?
With Azure CLI it's as easy as this
# Retrieve id for scope parameter
az vm show -n vm1 -o tsv --query id
# Create action group
az monitor action-group create -n action-group1 -g rg-training --action email admin [email protected]
# Create alert
az monitor metrics alert create -n alert2 -g rg-training --scopes "/subscriptions/<guid>/resourceGroups/rg-training/providers/Microsoft.Compute/virtualMachines/vm1" --condition "avg Percentage CPU > 90" --window-size 5m --evaluation-frequency 1m --action action-group1 --description "High CPU"
This is what my PowerShell attempts look like
Import-Module Az.Monitor
# Create a new condition
$condition = New-AzMetricAlertRuleV2Criteria -MetricName "Percentage CPU" -MetricNameSpace "Microsoft.Compute/virtualMachines" -TimeAggregation Average -Operator GreaterThan -Threshold 5
# Create new action group and receiver
$receiver = New-AzActionGroupReceiver -Name "Admin" -EmailReceiver -EmailAddress "[email protected]"
Set-AzActionGroup -Name "my-action-group" -ShortName "ActionGroup1" -ResourceGroupName "rg-training" -Receiver $receiver
# Retrieve resource id from vm1
$resourceID = get-azresource -name vm1 | Select-Object resourceid
# Finally add the alert rule that will trigger when for more then 5 min CPU percentage is more then 10%
Add-AzMetricAlertRuleV2 -Name "metricRule2" -ResourceGroupName "rg-training" -WindowSize 00:05:00 -Frequency 00:01:00 -TargetResourceId $resourceID -Condition $condition -ActionGroupId "my-action-group" -Severity 4
Which results in
> Add-AzMetricAlertRuleV2 : Exception type: ErrorResponseException,
> Message: Null/Empty, Code: Null, Status code:BadRequest, Reason
> phrase: Bad Request At C:\Temp\03 Create and test alerts.ps1:17 char:1
> + Add-AzMetricAlertRuleV2 -Name "metricRule2" -ResourceGroupName "rg-tr ...
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : CloseError: (:) [Add-AzMetricAlertRuleV2], PSInvalidOperationException
> + FullyQualifiedErrorId : Microsoft.Azure.Commands.Insights.Alerts.AddAzureRmMetricAlertRuleV2Command
What am I doing wrong here?
2.5.1Get-InstalledModule -name azaccording to this thread: github.com/Azure/azure-powershell/issues/… This bug have fixed for version 3.X