Search code examples
azurepowershellazure-powershellazure-virtual-machineazure-alerts

Issues Adding Azure Alerts via PS


I'm trying to automate the creation/assignment of alerts for Azure resources (specifically VMs right now, but more later) and I feel like I have everything set up properly, but I'm getting a bad request error every time. Google surprisingly didn't have much for me on this one, there doesn't seem to be a whole lot of troubleshooting documentation out there regarding this.

Here's what I have so far (I can paste to GitHub if this is too mangled in SO)

$Dim = New-AzMetricAlertRuleV2DimensionSelection -DimensionName "Computer" -ValuestoInclude "*"
$Condition = New-AzMetricAlertRuleV2Criteria -MetricName "Percentage CPU" -DimensionSelection $dim -TimeAggregation average -Operator GreaterThan -Threshold 95
$Target = Get-AzVM -Name [ServerName]
$ActionGroup = (Get-AzActionGroup -Name "[AGName]" -ResourceGroupName "[RGName]")
$AGID = New-AzActionGroup -ActionGroupId $ActionGroup.Id
Add-AzMetricAlertRuleV2 -Name "[ServerName] CPU Above 95%" -ResourceGroupName $Target.ResourceGroupName -WindowSize 0:5 -Frequency 0:5 -TargetResourceType "Microsoft.Compute/virtualMachines" -TargetResourceScope $Target.Id -TargetResourceRegion $Target.Location -Condition $Condition -ActionGroup $AGID -Severity 0

Below is the error I get:

Add-AzMetricAlertRuleV2 : Exception type: ErrorResponseException, Message: Null/Empty, Code: Null, Status

code:BadRequest, Reason phrase: Bad Request

At line:8 char:1

+ Add-AzMetricAlertRuleV2 -Name "[ServerName] Above 95%" -ResourceGrou ...

Now, I figure by that it's saying something is coming up null, but it's not specifying. It just states null/empty


Solution

  • So I had two issues in this script, both found by setting $DebugPreference to 'Continue'

    1. The Alert Rule had a % symbol in it, which for URL reasons cannot complete the API call

    2. After correcting that, I got this

      Add-AzMetricAlertRuleV2 : Exception type: ErrorResponseException, Message: The metric Percentage CPU specifies a
      dimension Computer which was not found. Activity ID: 9dc915e6-11d2-4ecd-bf0b-835d12e4051f., Code: BadRequest, Status
      code:BadRequest, Reason phrase: BadRequest
      
    3. Once I removed the $dim line and removed the -DimensionSelection option from my arguments, the alert created successfully