使用 Terraform 创建提醒政策

本文档介绍了如何使用 Google Cloud Terraform 提供程序在 Google Cloud 项目中创建提醒政策。Google Cloud Terraform 提供程序为提醒政策和通知渠道提供了以下资源:

Terraform 是一种用于构建、更改和版本控制基础架构的工具。它使用配置文件来描述运行单个应用或整个基础架构所需的组件。如需详细了解如何使用 Terraform,请参阅以下文档:

准备工作

如需获取使用 Terraform 创建提醒政策所需的权限,请让管理员授予您项目的 Monitoring Editor (roles/monitoring.editor) IAM 角色。如需详细了解如何授予角色,请参阅管理访问权限

您也可以通过自定义角色或其他预定义角色来获取所需的权限。

如需详细了解 Cloud Monitoring 角色,请参阅使用 Identity and Access Management 控制访问权限

创建提醒政策

如需在 Google Cloud 项目中创建提醒政策,请执行以下操作:

  1. 确保 Terraform 已安装在 Cloud Shell 中。

  2. 在 Cloud Shell 中,转到包含 Terraform 配置的目录。

  3. 修改配置文件并添加您的提醒政策。

    例如,以下配置定义了一项提醒政策,该政策会在某个虚拟机实例的 CPU 利用率超过 50% 且持续一分钟以上时发送通知,并且每 30 分钟发送一次重复通知

    resource "google_monitoring_alert_policy" "alert_policy" {
      display_name = "CPU Utilization > 50%"
      documentation {
        content = "The $${metric.display_name} of the $${resource.type} $${resource.label.instance_id} in $${resource.project} has exceeded 50% for over 1 minute."
      }
      combiner     = "OR"
      conditions {
        display_name = "Condition 1"
        condition_threshold {
            comparison = "COMPARISON_GT"
            duration = "60s"
            filter = "resource.type = \"gce_instance\" AND metric.type = \"compute.googleapis.com/instance/cpu/utilization\""
            threshold_value = "0.5"
            trigger {
              count = "1"
            }
        }
      }
    
      alert_strategy {
        notification_channel_strategy {
            renotify_interval = "1800s"
            notification_channel_names = [google_monitoring_notification_channel.email.name]
        }
      }
    
      notification_channels = [google_monitoring_notification_channel.email.name]
    
      user_labels = {
        severity = "warning"
      }
    }
    

    在上述示例中,notification_channels 字段定义了提醒政策的通知渠道。notification_channel_names 字段用于配置该通知渠道,以发送重复通知。这两个字段都引用 display_nameemail 的通知渠道,该渠道在 Terraform 配置中的其他位置定义。如需了解详情,请参阅使用 Terraform 创建和管理通知渠道

  4. 在 Cloud Shell 中,输入 terraform apply

如需修改提醒政策,请进行修改,然后重新应用 Terraform 配置。如需了解详情,请参阅使用 Terraform 管理提醒政策

后续步骤