You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Terraform在Azure中为单个资源创建多类警报(如VM的CPU等)

使用Terraform在Azure为虚拟机创建多维度监控警报

以下是针对单台Azure VM创建CPU使用率、内存使用率及磁盘I/O监控警报的具体实现步骤,所有配置均通过Terraform完成。

前提条件

  • 已在Azure中部署目标VM,记录其资源ID(可通过Azure Portal或az vm show命令获取)
  • Terraform已配置Azure Provider(确保版本≥3.0,避免兼容性问题)

1. 定义警报通知Action Group

首先创建Action Group,用于接收警报触发后的通知(示例为邮件通知,可按需扩展为短信、Webhook等):

resource "azurerm_monitor_action_group" "vm_alerts_action" {
  name                = "vm-alerts-action-group"
  resource_group_name = var.resource_group_name
  short_name          = "vm-alert-ag"

  email_receiver {
    name                    = "admin-email"
    email_address           = "admin@example.com"
    use_common_alert_schema = true
  }
}

2. 创建CPU使用率警报规则

监控VM的CPU使用率,当持续5分钟超过80%时触发警报:

resource "azurerm_monitor_metric_alert" "vm_cpu_alert" {
  name                = "vm-cpu-high-alert"
  resource_group_name = var.resource_group_name
  scopes              = [var.vm_id]
  description         = "Alert when VM CPU usage exceeds 80% for 5 minutes"
  severity            = 2

  criteria {
    metric_namespace = "Microsoft.Compute/virtualMachines"
    metric_name      = "Percentage CPU"
    aggregation      = "Average"
    operator         = "GreaterThan"
    threshold        = 80

    dimension {
      name     = "ResourceId"
      operator = "Include"
      values   = ["*"]
    }
  }

  action {
    action_group_id = azurerm_monitor_action_group.vm_alerts_action.id
  }

  frequency = "PT1M"
  window_size = "PT5M"
}

3. 创建内存使用率警报规则

注意:内存指标需要先为VM启用Azure诊断扩展,否则无法采集到相关数据。若未启用,可先添加以下诊断配置:

# 启用VM诊断扩展(可选,若已启用可跳过)
resource "azurerm_virtual_machine_extension" "vm_diagnostics" {
  name                 = "Microsoft.Insights.VMDiagnosticsSettings"
  virtual_machine_id   = var.vm_id
  publisher            = "Microsoft.Azure.Diagnostics"
  type                 = "IaaSDiagnostics"
  type_handler_version = "1.5"

  settings = jsonencode({
    StorageAccount = var.diagnostic_storage_account_name
    WadCfg = {
      DiagnosticMonitorConfiguration = {
        overallQuotaInMB = 4096
        Memory = {
          counters = [
            {
              counterSpecifier = "\\Memory\\% Committed Bytes In Use"
              sampleRateInSeconds = 60
            }
          ]
        }
      }
    }
  })

  protected_settings = jsonencode({
    storageAccountName = var.diagnostic_storage_account_name
    storageAccountKey  = var.diagnostic_storage_account_key
    storageAccountEndPoint = "https://${var.diagnostic_storage_account_name}.blob.core.windows.net"
  })
}

然后创建内存警报规则:

resource "azurerm_monitor_metric_alert" "vm_memory_alert" {
  name                = "vm-memory-high-alert"
  resource_group_name = var.resource_group_name
  scopes              = [var.vm_id]
  description         = "Alert when VM memory usage exceeds 85% for 5 minutes"
  severity            = 2

  criteria {
    metric_namespace = "Microsoft.Compute/virtualMachines"
    metric_name      = "MemoryPercentageUsed"
    aggregation      = "Average"
    operator         = "GreaterThan"
    threshold        = 85

    dimension {
      name     = "ResourceId"
      operator = "Include"
      values   = ["*"]
    }
  }

  action {
    action_group_id = azurerm_monitor_action_group.vm_alerts_action.id
  }

  frequency = "PT1M"
  window_size = "PT5M"
}

4. 创建磁盘I/O警报规则

以下示例创建磁盘写入字节数过高的警报,可按需调整为磁盘读取或使用率指标:

resource "azurerm_monitor_metric_alert" "vm_disk_write_alert" {
  name                = "vm-disk-write-high-alert"
  resource_group_name = var.resource_group_name
  scopes              = [var.vm_id]
  description         = "Alert when VM disk write bytes exceed 100MB/s for 5 minutes"
  severity            = 2

  criteria {
    metric_namespace = "Microsoft.Compute/virtualMachines"
    metric_name      = "Disk Write Bytes/sec"
    aggregation      = "Average"
    operator         = "GreaterThan"
    threshold        = 104857600 # 100MB/s 转换为字节数

    dimension {
      name     = "ResourceId"
      operator = "Include"
      values   = ["*"]
    }
  }

  action {
    action_group_id = azurerm_monitor_action_group.vm_alerts_action.id
  }

  frequency = "PT1M"
  window_size = "PT5M"
}

部署配置

完成上述代码编写后,执行以下Terraform命令部署:

  1. 初始化Terraform:terraform init
  2. 预览部署计划:terraform plan
  3. 应用配置:terraform apply

内容的提问来源于stack exchange,提问作者Mohamed Aslam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 16:48:25