Let go over a simple one – how to create various types of alert rules in Azure using the AZ PowerShell Module.
Each example targets a different aspect of Azure monitoring, but doesn’t cover them all. Remember to tweak the parameters to match your environment.
Metric Alerts for Performance Monitoring
To keep an eye on Azure service metrics:
$criteria = New-AzMetricAlertRuleV2Criteria -MetricName 'Percentage CPU' -TimeAggregation Average -Operator GreaterThan -Threshold 80 Add-AzMetricAlertRuleV2 -Name 'HighCPUAlert' -ResourceGroupName 'YourResourceGroupName' -WindowSize 00:05:00 -Frequency 00:01:00 -TargetResourceId '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/Microsoft.Compute/virtualMachines/yourVMName' -Condition $criteria -ActionGroup '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/actionGroups/yourActionGroupName' -Severity 3 -Description 'Alert on high CPU usage.'
Log Alerts for Custom Log Queries
For alerts based on log analytics:
$query = "AzureActivity | where OperationName == 'Create or Update Virtual Machine' and ActivityStatus == 'Succeeded'" Set-AzScheduledQueryRule -ResourceGroupName 'YourResourceGroupName' -Location 'East US' -ActionGroup '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/actionGroups/yourActionGroupName' -ConditionQuery $query -Description "VM creation alert" -Enabled $true -EvaluationFrequency 'PT5M' -Severity 0 -WindowSize 'PT5M' -Name 'VMCreationAlert'
Activity Log Alerts for Azure Resource Events
To monitor specific Azure service events:
$condition = New-AzActivityLogAlertCondition -Field 'category' -Equal 'Administrative' $actionGroupId = "/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/actionGroups/yourActionGroupName" Set-AzActivityLogAlert -Location 'Global' -Name 'AdminActivityAlert' -ResourceGroupName 'YourResourceGroupName' -Scopes "/subscriptions/yourSubscriptionId" -Condition $condition -ActionGroupId $actionGroupId -Description "Alert on administrative activities"
Application Insights Alerts for Application Performance
Track application performance with a simple AppInsights web test
$rule = New-AzApplicationInsightsWebTestAlertRule -Name 'AppPerfAlert' -ResourceGroupName 'YourResourceGroupName' -Location 'East US' -WebTestId '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/webtests/yourWebTestId' -FailedLocationCount 3 -WindowSize 'PT5M' -Frequency 'PT1M' -Criteria $criteria Set-AzApplicationInsightsWebTestAlertRule -InputObject $rule