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

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

Slack 等服務提供傳入 Webhook,可讓應用程式輕鬆將訊息發布到 Slack。Cloud Run functions 是一項輕量型 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. 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎 建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,能用於執行、測試及部署工作負載。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the GKE, Cloud Run functions, Cloud Build, Eventarc and Pub/Sub APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    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. 初始化 gcloud CLI 後,請更新 gcloud CLI 並安裝必要元件:

    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.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  10. Verify that billing is enabled for your Google Cloud project.

  11. Enable the GKE, Cloud Run functions, Cloud Build, Eventarc and Pub/Sub APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    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. 初始化 gcloud CLI 後,請更新 gcloud CLI 並安裝必要元件:

    gcloud components update
    gcloud components install alpha beta
  16. 啟用 GKE 叢集通知。

必要的角色

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

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

Slack 通知

如要設定 Slack 通知,請建立 Slack 應用程式、為該應用程式啟用「傳入 Webhook」,然後將應用程式安裝至 Slack 工作區。

建立 Slack 應用程式

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

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

  3. 建立新的 Slack 應用程式

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

編寫 Cloud Run 函式

GKE 將叢集通知發布至 Pub/Sub 主題時,該事件會觸發 Cloud Run functions 傳送 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);
            (async () => {
              await webhook.send(message);
            })().catch((e) => {
                console.log(e);
            });
        }
    });
    
    // 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 網址,然後將訊息傳送至設定的 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.js 和 package.json 檔案。

部署 Cloud Run 函式

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

gcloud

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

gcloud functions deploy slackNotifier \
  --gen2 \
  --trigger-topic=TOPIC_NAME \
  --runtime=nodejs24 \
  --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: nodejs24
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. 在「Configuration」(設定) 頁面中,執行下列步驟:

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

    1. 在「執行階段」下拉式選單中,選取「Node.js 24」。
    2. 在「Entry point」(進入點) 中,指定「slackNotifier」。
    3. 在導覽窗格中選取 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. 前往 Google Cloud 控制台的「Manage resources」(管理資源) 頁面。

    前往「Manage resources」(管理資源)

  2. 在專案清單中選取要刪除的專案,然後點選「Delete」(刪除)。
  3. 在對話方塊中輸入專案 ID,然後按一下 [Shut down] (關閉) 以刪除專案。

刪除個別資源

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

    gcloud functions delete slackNotifier
    

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

  2. 刪除 Pub/Sub 主題。

  3. 刪除 Slack 應用程式。

後續步驟