為第三方服務設定叢集通知


本教學課程說明如何設定第三方訊息服務,以接收 Google Kubernetes Engine (GKE) 叢集通知

Slack 等服務提供「連入 Webhook」,可讓您輕鬆將應用程式中的訊息發布到 Slack。Cloud Run 函式是輕量級的 Compute Engine 解決方案,可建立獨立的單一用途函式來回應Google Cloud 事件,例如叢集通知,不必管理伺服器或執行階段環境。GKE 使用 Pub/Sub 傳送叢集通知時,「觸發條件」會執行動作來回應,例如傳送 Slack 通知。

有許多使用跨應用程式訊息傳遞功能建構的第三方服務,例如 IFTTT。您可以使用本教學課程做為範本,與這些服務連線。

在本教學課程中,您將使用 Cloud Run 函式和 Pub/Sub,將 GKE 叢集事件的通知傳送至 Slack。

目標

  • 部署 Slack 應用程式,接收來自 GKE 的外部通知。
  • 撰寫 Cloud Run 函式,將 Pub/Sub 通知傳送給 Slack。

費用

在本文件中,您會使用 Google Cloud的下列計費元件:

如要根據預測用量估算費用,請使用 Pricing Calculator

初次使用 Google Cloud 的使用者可能符合免費試用資格。

完成本文所述工作後,您可以刪除已建立的資源,避免繼續計費。詳情請參閱清除所用資源一節。

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the GKE, Cloud Run functions, Cloud Build, Eventarc and Pub/Sub APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. To initialize the gcloud CLI, run the following command:

    gcloud init
  8. After initializing the gcloud CLI, update it and install the required components:

    gcloud components update
    gcloud components install alpha beta
  9. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  10. Make sure that billing is enabled for your Google Cloud project.

  11. Enable the GKE, Cloud Run functions, Cloud Build, Eventarc and Pub/Sub APIs.

    Enable the APIs

  12. Install the Google Cloud CLI.

  13. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  14. To initialize the gcloud CLI, run the following command:

    gcloud init
  15. After initializing the gcloud CLI, update it and install the required components:

    gcloud components update
    gcloud components install alpha beta
  16. 啟用 GKE 叢集通知。
  17. 必要的角色

    如要取得設定叢集通知 Slack 通知所需的權限,請要求管理員為您授予專案的下列 IAM 角色:

    為確保 Compute Engine 預設服務帳戶具備叫用 Cloud Run 函式的必要權限, 請管理員授予 Compute Engine 預設服務帳戶專案的 Cloud Functions 叫用者 (roles/cloudfunctions.invoker) IAM 角色。

Slack 通知

如要設定 Slack 通知,您必須建立 Slack 應用程式、啟用應用程式的傳入 Webhook,並將應用程式安裝至 Slack 工作區。

建立 Slack 應用程式

  1. 加入 Slack 工作區,方法是註冊電子郵件或使用工作區管理員傳送的邀請。

  2. 使用工作區名稱和 Slack 帳戶憑證登入 Slack

  3. 建立新的 Slack 應用程式

    1. 在「建立應用程式」對話方塊中,按一下「從頭開始」
    2. 指定「應用程式名稱」,然後選擇 Slack 工作區。
    3. 點選「建立應用程式」
    4. 在「新增功能」下方,按一下「連入的 Webhook」
    5. 按一下「啟用連入的 Webhook」切換按鈕。
    6. 在「Webhook URLs for Your Workspace」部分,按一下「Add New Webhook to Workspace」
    7. 在隨即開啟的授權頁面中,選取要接收通知的頻道。
    8. 按一下「Allow」
    9. Slack 應用程式的 Webhook 會顯示在「Webhook URLs for Your Workspace」(工作區的 Webhook 網址) 部分。請儲存這個網址,稍後會用到。

編寫 Cloud Run 函式

當 GKE 將叢集通知發布至 Pub/Sub 主題時,事件會觸發 Cloud Run 函式,進而傳送 Slack 通知。

  1. 建立一個新目錄並命名為 gke_slack,然後將目錄變更為該目錄:

    mkdir ~/gke_slack && cd $_
    
  2. 在 gke_slack 目錄中建立下列檔案:

    index.js

    const functions = require('@google-cloud/functions-framework');
    const { IncomingWebhook } = require('@slack/webhook');
    
    const url = process.env.SLACK_WEBHOOK;
    
    const webhook = new IncomingWebhook(url);
    
    // Optionally filter what notification types to forward to Slack.
    // If empty, all types will be allowed.
    const allowedTypeURLs = [];
    
    // Register a CloudEvent callback with the Functions Framework that will
    // be executed when the Pub/Sub trigger topic receives a message.
    functions.cloudEvent('slackNotifier', pubSubEvent => {
        const data = decode(pubSubEvent.data.message.data);
    
        // Send message to Slack.
        if (isAllowedType(pubSubEvent.data.message.attributes)) {
            const message = createSlackMessage(data, pubSubEvent.data.message.attributes);
            webhook.send(message);
        }
    });
    
    // decode decodes a pubsub event message from base64.
    const decode = (data) => {
        return Buffer.from(data, 'base64').toString();
    }
    
    // isAllowedType can be used to filter out messages that don't match the
    // allowed type URLs. If allowedTypeURLs is empty, it allows all types.
    const isAllowedType = (attributes) => {
        if (allowedTypeURLs.length == 0) {
            return true;
        }
        for (var x in allowedTypeURLs) {
            if (attributes['type_url'] == allowedTypeURLs[x]) {
                return true;
            }
        }
        return false;
    }
    
    // createSlackMessage creates a message from a data object.
    const createSlackMessage = (data, attributes) => {
        // Write the message data and attributes.
        text = `${data}`
        for (var key in attributes) {
            if (attributes.hasOwnProperty(key)) {
                text = text + `\n\t\`${key}: ${attributes[key]}\``
            }
        }
        const message = {
            text: text,
            mrkdwn: true,
        };
        return message;
    }
    

    SLACK_WEBHOOK 是 Cloud Run 函式環境變數,用於指定為 Slack 應用程式建立的 Webhook 網址。部署函式時,您會定義環境變數。

    Webhook 會接聽並接收來自 Cloud Run functions 的訊息。當 GKE 將叢集通知傳送至 Pub/Sub (事件) 時,函式會將訊息 (觸發條件) 傳送至 Webhook URL,然後將訊息傳送至設定的 Slack 工作區。

    您可以在 createSlackMessage 函式中展開訊息,以顯示更多內容,包括文字格式和圖片。系統提供 isAllowedType 函式,可依類型網址基本篩選通知。您可以在 allowedTypeURLs 中指定允許的網址類型。如果您已在 GKE 或 Pub/Sub 訂閱項目中篩選通知,就不需要使用這項函式。

    package.json

    {
      "name": "gke-slack",
      "version": "0.0.1",
      "description": "Slack integration for GKE, using Cloud Run functions",
      "main": "index.js",
      "dependencies": {
        "@slack/webhook": "6.1.0",
        "@google-cloud/functions-framework": "^3.0.0"
      }
    }
    

    package.json 說明計畫的下列屬性:

    • 名稱、版本和說明
    • 主要執行階段檔案
    • 依附元件

    您可以視需要新增更多依附元件、需求及其他資訊。

gke_slack 目錄中現在應該會有 index.jspackage.json 檔案。

部署 Cloud Run 函式

您可以使用 Google Cloud CLI 或 Google Cloud 控制台部署 Cloud Run 函式。

gcloud

如要部署函式,請在 gke_slack 目錄中執行下列指令:

gcloud functions deploy slackNotifier \
  --gen2 \
  --trigger-topic=TOPIC_NAME \
  --runtime=nodejs14 \
  --entry-point=slackNotifier \
  --region=REGION \
  --source=. \
  --set-env-vars="SLACK_WEBHOOK=WEBHOOK_URL"

更改下列內容:

  • TOPIC_NAME:您啟用叢集通知時建立的 Pub/Sub 主題名稱。
  • REGION:函式的 Compute Engine 區域。
  • WEBHOOK_URL:在「建立 Slack 應用程式」中,為 Slack 應用程式建立的 Webhook 網址。

輸出結果會與下列內容相似:

Deploying function…
availableMemoryMb: 256
entryPoint: slackNotifier
environmentVariables:
  SLACK_WEBHOOK: https://hooks.slack.com/services/…
eventTrigger:
  eventType: google.pubsub.topic.publish
  failurePolicy: {}
  resource: projects/PROJECT_ID/topics/TOPIC_NAME
  service: pubsub.googleapis.com
labels:
  deployment-tool: cli-gcloud
name: projects/PROJECT_ID/locations/us-central1/functions/slackNotifier
runtime: nodejs10
serviceAccountEmail: PROJECT_ID@appspot.gserviceaccount.com
sourceUploadUrl: https://storage.googleapis.com/…
status: ACTIVE
timeout: 60s
updateTime: 'YYYY-MM-DDThh:mm:ssZ'
versionId: '1'

控制台

  1. 前往 Google Cloud 控制台的「Cloud Run functions」頁面。

    前往「Cloud Functions」頁面

  2. 按一下「建立函式」

  3. 在「設定」頁面中,執行下列步驟:

    1. 在「環境」下拉式清單中,選取「第 2 代」
    2. 在「Function name」(函式名稱) 中,指定 slackNotifier
    3. 在「Region」中,指定 Compute Engine 區域。
    4. 在「觸發條件」部分中,按一下「新增 Eventarc 觸發條件」
    5. 在開啟的視窗中,確認「Event provider」(事件提供者) 下拉式清單已選取「Cloud Pub/Sub」
    6. 選取您在啟用叢集通知時建立的 Pub/Sub 主題。
    7. 在「Region」(區域) 中,指定與函式相同的 Compute Engine 區域。
    8. 按一下「儲存觸發條件」
    9. 展開「執行階段、建構作業、連線和安全性設定」專區。
    10. 在「執行階段環境變數」下方,按一下 「新增變數」
    11. 將「Name」(名稱) 指定為「SLACK_WEBHOOK」
    12. 在「值」中,指定在「建立 Slack 應用程式」中建立的內部 Webhook 網址。
    13. 點選「下一步」
  4. 在「程式碼」頁面中,執行下列步驟:

    1. 從「Runtime」(執行階段) 下拉式選單中選取「Node.js 14」
    2. 在「Entry point」(進入點) 中,指定 slackNotifier
    3. 在導覽窗格中選取「index.js」index.js,然後將程式碼替換為「編寫 Cloud 函式」中的範例程式碼。
    4. 在導覽窗格中選取「package.json」package.json,然後將程式碼替換為「編寫 Cloud Function」中的範例程式碼。
    5. 按一下 [Deploy] (部署)

完成 Cloud Run 函式的部署作業之後,每當 GKE 傳送叢集通知,您就會收到 Slack 通知。

確認 Slack 通知

如果您使用 Autopilot 叢集,請按照下列步驟驗證通知:

  1. 啟動控制層升級
  2. 等待 GKE 自動將節點升級至新版本。實際所需時間可能因設定的維護期間和排除時段而異。
  3. GKE 升級節點後,請查看 Slack 訊息。

如果您使用標準叢集,請按照下列方式驗證通知:

  1. 將特定節點集區升級至新版本。 如果不想變更節點上的 GKE 版本,可以升級至節點目前使用的版本。

  2. GKE 升級節點後,請查看 Slack 訊息。

Slack 通知類似於下列內容:

Master is upgrading to version 1.20.10-gke.301.
    cluster_location: us-central1
    cluster_name: pubsub-cluster
    payload: {"resourceType":"MASTER", "operation":"operation-1632775054313-45128f4f", "operationStartTime":"2021-09-27T20:37:34.313742491Z", "currentVersion":"1.20.9-gke.1001", "targetVersion":"1.20.10-gke.301"}
    project_id: 729788050015
    type_url: type.googleapis.com/google.container.v1beta1.UpgradeEvent

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。

刪除專案

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

刪除個別資源

  1. 刪除您在本教學課程中部署的 Cloud Run 函式:

    gcloud functions delete slackNotifier
    

    您也可以從 Google Cloud 控制台刪除 Cloud Run 函式。

  2. 刪除 Pub/Sub 主題

  3. 刪除 Slack 應用程式

後續步驟