Skip to content

Instantly share code, notes, and snippets.

@matthiasguentert
Created July 26, 2021 19:25
Show Gist options
  • Save matthiasguentert/868a3eca8492e5f0f32b40dec814813a to your computer and use it in GitHub Desktop.
Save matthiasguentert/868a3eca8492e5f0f32b40dec814813a to your computer and use it in GitHub Desktop.
How to create an Azure alert rule

Azure CLI version

az monitor action-group create --name ag-notify-admins --resource-group rg-training --action email action-send-mail admin@host.org

# Install App Insights extension (requires Azure CLI 2.0.79 or higher)
az extension add --name application-insights 

# Retrieve resource id 
$scope = az monitor app-insights component show --app appi-demo --resource-group rg-training --query id --output tsv

# Alternatively if you don't want to install the app insights extension 
$scope = az resource show --name appi-demo --resource-group rg-training --resource-type microsoft.insights/components --query id --output tsv

# Create the actual metric alert
az monitor metrics alert create --name alert-on-exceptions --resource-group rg-training --scopes $scope --condition "count exceptions/count > 10" --window-size 5m --evaluation-frequency 1m --action ag-notify-admins --description "High exception rate" 

Azure PowerShell version

$receiver = New-AzActionGroupReceiver -Name "Admin" -EmailAddress "admin@host.org"

# Creates a new or updates an existing action group
$actionGroup = Set-AzActionGroup -name "ag-notify-admins" -ShortName "ActionGroup1" -ResourceGroupName "rg-training" -Receiver $receiver

# Read back action group and store id in variable 
$actionGroupId = New-AzActionGroup -ActionGroupId $actionGroup.Id

# Create a new condition
$condition = New-AzMetricAlertRuleV2Criteria -MetricName "exceptions/count" -TimeAggregation Count -Operator GreaterThan -Threshold 10

# Get resource id of app insights 
$scope = (Get-AzApplicationInsights -ResourceGroupName rg-training -name appi-demo).id

# Finally bring the pieces together
$windowSize = New-TimeSpan -Minutes 5
$frequency = New-TimeSpan -Minutes 1
Add-AzMetricAlertRuleV2 -name "alert-on-high-exceptions" -ResourceGroupName rg-training -WindowSize $windowSize -Frequency $frequency -TargetResourceId $scope -Condition $condition -ActionGroup $actionGroup.id -Severity 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment