如何将Azure VM告警规则脚本改造为跨订阅/资源组的自动化脚本
改造Azure VM告警脚本为自动化版本的步骤
问题背景
现有PowerShell脚本可创建Azure VM的监控告警规则,但每次适配不同订阅、资源组的VM时,需手动修改告警名称、目标资源范围等信息,无法批量自动化处理。
改造步骤
- 提取可配置参数:将订阅ID、动作组ID、告警规则名称前缀、目标资源组(可选)、告警阈值等硬编码值,改为脚本参数,运行时可灵活传入。比如用
param块定义参数,支持指定单个/多个订阅、资源组,或覆盖默认阈值。 - 动态获取目标VM:使用
Get-AzVMcmdlet自动拉取指定范围内的所有VM(可指定资源组,或全订阅),无需手动逐个指定VM名称和资源路径。 - 重构告警规则配置:把每个告警的指标名称、阈值、窗口大小、频率、描述等信息整理成一个配置数组,循环遍历每个VM和每个告警配置,自动拼接告警规则名称、生成目标资源范围路径。
- 增加幂等性检查:在创建告警规则前,先通过
Get-AzMetricAlertRuleV2检查同名规则是否已存在,避免重复创建导致报错。 - 支持多订阅切换:如果需要适配多个订阅,添加订阅遍历逻辑,先切换到目标订阅,再执行VM获取和告警创建操作。
改造后的示例脚本
param( [Parameter(Mandatory=$true)] [string[]]$SubscriptionIds, [Parameter(Mandatory=$true)] [string]$ActionGroupResourceId, [string]$AlertRulePrefix = "ClientName - Virtual machines", [string]$TargetResourceGroupName, # 留空则处理订阅下所有资源组的VM [int]$CpuThreshold = 96, [long]$MemoryThreshold = 1000000000, [int]$DiskIopsThreshold = 95, [int]$VmAvailabilityThreshold = 1 ) # 定义告警规则配置数组 $alertConfigs = @( @{ MetricName = "Percentage CPU" Operator = "GreaterThan" Threshold = $CpuThreshold WindowSize = "0:30" Frequency = "0:15" Description = "Action will be triggered when CPU usage is greater than threshold" Severity = 0 }, @{ MetricName = "Available Memory Bytes" Operator = "LessThan" Threshold = $MemoryThreshold WindowSize = "0:30" Frequency = "0:30" Description = "Action will be triggered when Available Memory Bytes is less than threshold" Severity = 0 }, @{ MetricName = "Data Disk IOPS Consumed Percentage" Operator = "GreaterThan" Threshold = $DiskIopsThreshold WindowSize = "1:0" Frequency = "0:30" Description = "Action will be triggered when Data Disk IOPS usage is greater than threshold" Severity = 0 }, @{ MetricName = "OS Disk IOPS Consumed Percentage" Operator = "GreaterThan" Threshold = $DiskIopsThreshold WindowSize = "1:0" Frequency = "0:30" Description = "Action will be triggered when OS Disk IOPS usage is greater than threshold" Severity = 0 }, @{ MetricName = "VmAvailabilityMetric" Operator = "LessThan" Threshold = $VmAvailabilityThreshold WindowSize = "0:15" Frequency = "0:15" Description = "Action will be triggered when VM Availability is less than threshold." Severity = 0 } ) # 初始化动作组对象 $actionGroup = [Microsoft.Azure.Management.Monitor.Management.Models.ActivityLogAlertActionGroup]::New($ActionGroupResourceId) # 遍历每个订阅 foreach ($subId in $SubscriptionIds) { # 切换到目标订阅 Set-AzContext -Subscription $subId | Out-Null Write-Host "Processing subscription: $subId" # 获取目标VM $vms = if ($TargetResourceGroupName) { Get-AzVM -ResourceGroupName $TargetResourceGroupName } else { Get-AzVM } if (-not $vms) { Write-Host "No VMs found in subscription $subId" continue } # 遍历每个VM foreach ($vm in $vms) { $vmName = $vm.Name $vmResourceGroup = $vm.ResourceGroupName $vmRegion = $vm.Location $vmResourceId = $vm.Id Write-Host "Processing VM: $vmName in resource group $vmResourceGroup" # 遍历每个告警配置 foreach ($config in $alertConfigs) { # 生成告警规则名称 $alertRuleName = "$AlertRulePrefix - $vmName - $($config.MetricName) - Critical" # 检查告警规则是否已存在 $existingRule = Get-AzMetricAlertRuleV2 -ResourceGroupName $vmResourceGroup -Name $alertRuleName -ErrorAction SilentlyContinue if ($existingRule) { Write-Host "Alert rule '$alertRuleName' already exists, skipping..." continue } # 创建告警条件 $criteria = New-AzMetricAlertRuleV2Criteria ` -MetricName $config.MetricName ` -MetricNameSpace "Microsoft.Compute/virtualMachines" ` -TimeAggregation Average ` -Operator $config.Operator ` -Threshold $config.Threshold # 创建告警规则 try { Add-AzMetricAlertRuleV2 ` -Name $alertRuleName ` -ResourceGroupName $vmResourceGroup ` -WindowSize $config.WindowSize ` -Frequency $config.Frequency ` -TargetResourceScope $vmResourceId ` -TargetResourceType "Microsoft.Compute/virtualMachines" ` -TargetResourceRegion $vmRegion ` -Description $config.Description ` -Severity $config.Severity ` -ActionGroup $actionGroup ` -Condition $criteria Write-Host "Successfully created alert rule: $alertRuleName" } catch { Write-Error "Failed to create alert rule '$alertRuleName': $_" } } } }
使用说明
- 运行脚本时,传入必填参数:
.\Automate-VMAlerts.ps1 -SubscriptionIds "sub-id-1","sub-id-2" -ActionGroupResourceId "/subscriptions/xxx/resourceGroups/alert/providers/Microsoft.Insights/actiongroups/alertaction" - 可选参数:指定
-TargetResourceGroupName处理单个资源组的VM,或调整阈值参数覆盖默认值。
内容的提问来源于stack exchange,提问作者Md Nizam Uddin
相关产品推荐
相关产品推荐

