使用 Terraform 建立快訊政策

本文說明如何使用 Google Cloud Terraform 供應商在 Google Cloud 專案中建立警報政策。 Google Cloud Terraform 供應商 提供下列快訊政策和通知管道資源:

Terraform 是一種工具,可建構、變更基礎架構,並管理基礎架構版本。並使用設定檔描述執行單一應用程式或整個基礎架構所需的元件。如要進一步瞭解如何使用 Terraform,請參閱下列文件:

事前準備

如要取得使用 Terraform 建立快訊政策所需的權限,請要求管理員為您授予專案的Monitoring 編輯者 (roles/monitoring.editor) 身分與存取權管理角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

您或許還可透過自訂角色或其他預先定義的角色取得必要權限。

如要進一步瞭解 Cloud Monitoring 角色,請參閱「使用 Identity and Access Management 控制存取權」。

建立快訊政策

如要在 Google Cloud 專案中建立快訊政策,請按照下列步驟操作:

  1. 安裝及設定 Terraform

  2. 在 Cloud Shell 中,前往包含 Terraform 設定的目錄。

  3. 編輯設定檔並新增快訊政策。

    舉例來說,下列設定定義的快訊政策會在 VM 執行個體的 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 建立及管理通知管道」。

    您可以使用標籤,將快訊政策與 App Hub 應用程式建立關聯。詳情請參閱「如何將快訊政策與 App Hub 應用程式建立關聯」。

  4. 在 Cloud Shell 中輸入 terraform apply

如要修改快訊政策,請編輯並重新套用 Terraform 設定。詳情請參閱「使用 Terraform 管理快訊政策」一文。

後續步驟

  • 進一步瞭解 Terraform
  • 試用使用Google Cloud Terraform Provider 和 Cloud Monitoring 的程式碼範例。
  • 在 GitHub 上查看 Google Cloud Terraform 供應商存放區
  • 如要回報錯誤或詢問 Terraform 相關問題,請在 GitHub 上提出問題