使用 Terraform 建立快訊政策

Google Cloud Terraform 供應商可讓您在Google Cloud 專案中建立警告政策,監控服務和資源。您可以使用 google_monitoring_alert_policy 和 google_monitoring_notification_channel 資源設定這些政策及其通知管道。

Terraform 會使用設定檔,建構、變更及版本化執行單一應用程式或整個基礎架構所需的元件。如要進一步瞭解如何使用 Terraform,請參閱 Terraform on Google Cloud 說明文件、Google Cloud Terraform Provider 參考資料,以及開始使用 - Google Cloud。

事前準備

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

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

如要進一步瞭解 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 = "50"
            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_name 為 email 的通知管道,該管道在 Terraform 設定的其他位置定義。詳情請參閱「使用 Terraform 建立及管理通知管道」。

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

  4. 在 Cloud Shell 中輸入 terraform apply。

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

後續步驟

  • 進一步瞭解 Terraform。
  • 試用搭配 Cloud Monitoring 使用Google Cloud Terraform Provider 的程式碼範例。
  • 查看 Google Cloud Terraform Provider GitHub 存放區。
  • 提交 GitHub 問題,回報錯誤或詢問 Terraform 相關問題。