使用 Eventarc 透過 Cloud Storage 觸發函式


本教學課程將說明如何在 Cloud Run 中部署事件驅動函式,並使用 Eventarc 觸發函式,以回應使用 Google Cloud CLI 的 Cloud Storage 事件。

指定 Eventarc 觸發條件的篩選器後,您就能設定事件的路由,包括事件來源和事件目標。在本教學課程的範例中,Cloud Storage 值區的更新會觸發事件,並以 HTTP 要求的形式將要求傳送至函式。

目標

在這個教學課程中,您將執行下列操作:

  1. 建立 Cloud Storage bucket 做為事件來源
  2. 部署事件導向函式
  3. 建立 Eventarc 觸發條件
  4. 將檔案上傳至 Cloud Storage 來觸發函式

費用

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

您可以使用 Pricing Calculator 根據預測用量產生預估費用。 新 Google Cloud 使用者可能符合申請免費試用的資格。

事前準備

貴機構定義的安全性限制,可能會導致您無法完成下列步驟。如需疑難排解資訊,請參閱「在受限的 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. Install the Google Cloud CLI.

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

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

    gcloud init
  5. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

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

  7. Install the Google Cloud CLI.

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

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

    gcloud init
  10. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

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

  12. 如果您未使用 Cloud Shell,請更新 Google Cloud CLI 元件,並使用您的帳戶登入:
    gcloud components update
    gcloud auth login
  13. 啟用 API:
    gcloud services enable artifactregistry.googleapis.com \
        cloudbuild.googleapis.com \
        eventarc.googleapis.com \
        run.googleapis.com \
        storage.googleapis.com
  14. 設定本教學課程中要使用的設定變數:
    export REGION=us-central1
    gcloud config set run/region ${REGION}
    gcloud config set run/platform managed
    gcloud config set eventarc/location ${REGION}
  15. 如果您適用網域限制組織政策,且該政策限制專案的未經驗證叫用,您就必須按照「測試私人服務」一節的說明存取已部署的服務。

設定必要角色

您或管理員必須為部署者帳戶、觸發器身分,以及 Pub/Sub 服務代理人和 Cloud Storage 服務代理人授予下列 IAM 角色 (選用)。

部署者帳戶的必要角色

  1. 如果您是專案建立者,系統會授予您基本擁有者角色 (roles/owner)。根據預設,這個身分與存取權管理 (IAM) 角色會包含完整存取大多數 Google Cloud資源所需的權限,因此您可以略過這個步驟。

    如果您不是專案建立者,則必須將必要權限授予專案中的適當實體。舉例來說,主體可以是 Google 帳戶 (適用於使用者),也可以是服務帳戶 (適用於應用程式和運算工作負載)。詳情請參閱活動目的地的角色和權限頁面。

    如要取得完成本教學課程所需的權限,請要求管理員為您授予專案的下列 IAM 角色:

    如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

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

    請注意,根據預設,Cloud Build 權限包含上傳及下載 Artifact Registry 構件的權限。

觸發條件身分的必要角色

  1. 請記下 Compute Engine 預設服務帳戶,因為您會將其附加至 Eventarc 觸發事件,以便代表觸發事件的身分,用於測試用途。啟用或使用使用 Compute Engine 的 Google Cloud 服務後,系統會自動建立這個服務帳戶,且電子郵件格式如下:

    PROJECT_NUMBER-compute@developer.gserviceaccount.com

    PROJECT_NUMBER 替換為您的 Google Cloud專案編號。您可以在 Google Cloud 控制台的「歡迎」頁面上找到專案編號,也可以執行下列指令:

    gcloud projects describe PROJECT_ID --format='value(projectNumber)'

    對於實際環境,我們強烈建議建立新的服務帳戶,並授予一或多個包含必要最低權限的 IAM 角色,並遵循最低權限原則。

  2. 根據預設,只有專案擁有者、專案編輯者,以及 Cloud Run 管理員和叫用者可以叫用 Cloud Run 服務。您可以依服務控制存取權,但為了測試,請將 Google Cloud 專案的 Cloud Run 叫用者角色 (run.invoker) 授予 Compute Engine 服務帳戶。這樣一來,系統就會為專案中的所有 Cloud Run 服務和工作授予這個角色。
    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \
        --role=roles/run.invoker

    請注意,如果您為經過驗證的 Cloud Run 服務建立觸發條件,但未授予 Cloud Run 叫用者角色,系統會成功建立觸發條件並啟用。不過,觸發條件無法正常運作,而且記錄中會顯示類似以下的訊息:

    The request was not authenticated. Either allow unauthenticated invocations or set the proper Authorization header.
  3. 將專案的 Eventarc 事件接收者角色 (roles/eventarc.eventReceiver) 授予 Compute Engine 預設服務帳戶,以便 Eventarc 觸發條件接收事件供應商的事件。
    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \
        --role=roles/eventarc.eventReceiver

Cloud Storage 服務代理的選用角色

  • 為 Cloud Storage 的直接事件建立觸發條件之前,請先將 Pub/Sub 發布者角色 (roles/pubsub.publisher) 授予 Cloud Storage 服務代理:

    SERVICE_ACCOUNT="$(gcloud storage service-agent --project=PROJECT_ID)"
    
    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member="serviceAccount:${SERVICE_ACCOUNT}" \
        --role='roles/pubsub.publisher'

Pub/Sub 服務代理人的選用角色

  • 如果您是在 2021 年 4 月 8 日當天或之前啟用 Cloud Pub/Sub 服務代理,以便支援經過驗證的 Pub/Sub 推送要求,請將 服務帳戶權杖建立者角色 (roles/iam.serviceAccountTokenCreator) 授予服務代理。否則,系統會預設授予這個角色:
    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-pubsub.iam.gserviceaccount.com \
        --role=roles/iam.serviceAccountTokenCreator

建立 Cloud Storage 值區

建立要用做事件來源的 Cloud Storage bucket:

gcloud storage buckets create -l us-central1 gs://PROJECT_ID-bucket/

編寫事件導向函式

如要編寫事件導向函式,請按照下列步驟操作:

Node.js

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

       mkdir helloGCS
       cd helloGCS
    

  2. helloGCS 目錄中建立 package.json 檔案,指定 Node.js 依附元件:

    {
      "name": "nodejs-docs-samples-functions-v2-storage",
      "version": "0.0.1",
      "private": true,
      "license": "Apache-2.0",
      "author": "Google LLC",
      "repository": {
        "type": "git",
        "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
      },
      "engines": {
        "node": ">=16.0.0"
      },
      "scripts": {
        "test": "c8 mocha -p -j 2 test/*.test.js --timeout=60000"
      },
      "dependencies": {
        "@google-cloud/functions-framework": "^3.0.0"
      },
      "devDependencies": {
        "c8": "^10.0.0",
        "mocha": "^10.0.0",
        "sinon": "^18.0.0",
        "supertest": "^7.0.0"
      }
    }
    
  3. 使用下列 Node.js 範例,在 helloGCS 目錄中建立 index.js 檔案:

    const functions = require('@google-cloud/functions-framework');
    
    // Register a CloudEvent callback with the Functions Framework that will
    // be triggered by Cloud Storage.
    functions.cloudEvent('helloGCS', cloudEvent => {
      console.log(`Event ID: ${cloudEvent.id}`);
      console.log(`Event Type: ${cloudEvent.type}`);
    
      const file = cloudEvent.data;
      console.log(`Bucket: ${file.bucket}`);
      console.log(`File: ${file.name}`);
      console.log(`Metageneration: ${file.metageneration}`);
      console.log(`Created: ${file.timeCreated}`);
      console.log(`Updated: ${file.updated}`);
    });

Python

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

       mkdir helloGCS
       cd helloGCS
    

  2. helloGCS 目錄中建立 requirements.txt 檔案,以指定 Python 依附元件:

    functions-framework==3.8.2
    cloudevents==1.11.0

    這會新增範例所需的套件。

  3. 使用下列 Python 範例,在 helloGCS 目錄中建立 main.py 檔案:

    from cloudevents.http import CloudEvent
    
    import functions_framework
    
    
    # Triggered by a change in a storage bucket
    @functions_framework.cloud_event
    def hello_gcs(cloud_event: CloudEvent) -> tuple:
        """This function is triggered by a change in a storage bucket.
    
        Args:
            cloud_event: The CloudEvent that triggered this function.
        Returns:
            The event ID, event type, bucket, name, metageneration, and timeCreated.
        """
        data = cloud_event.data
    
        event_id = cloud_event["id"]
        event_type = cloud_event["type"]
    
        bucket = data["bucket"]
        name = data["name"]
        metageneration = data["metageneration"]
        timeCreated = data["timeCreated"]
        updated = data["updated"]
    
        print(f"Event ID: {event_id}")
        print(f"Event type: {event_type}")
        print(f"Bucket: {bucket}")
        print(f"File: {name}")
        print(f"Metageneration: {metageneration}")
        print(f"Created: {timeCreated}")
        print(f"Updated: {updated}")
    
        return event_id, event_type, bucket, name, metageneration, timeCreated, updated
    
    

部署事件導向函式

在包含範例程式碼的目錄中執行下列指令,即可部署名為 helloworld-events 的函式:

Node.js

gcloud run deploy helloworld-events \
      --source . \
      --function helloGCS \
      --base-image BASE_IMAGE \
      --region us-central1

BASE_IMAGE 替換為函式的基礎映像檔環境,例如 nodejs22。如要進一步瞭解基礎映像檔和各個映像檔中包含的套件,請參閱「支援的語言執行階段和基礎映像檔」。

Python

gcloud run deploy helloworld-events \
      --source . \
      --function hello_gcs \
      --base-image BASE_IMAGE \
      --region us-central1

BASE_IMAGE 替換為函式的基礎映像檔環境,例如 python313。如要進一步瞭解基礎映像檔和各個映像檔中包含的套件,請參閱「支援的語言執行階段和基礎映像檔」。

部署完成後,Google Cloud CLI 會顯示服務執行的網址。

建立 Eventarc 觸發條件

Eventarc 觸發條件會將 Cloud Storage 值區中的事件傳送至 helloworld-events Cloud Run 服務。

  1. 建立用來篩選 Cloud Storage 事件的觸發條件:

    gcloud eventarc triggers create TRIGGER_NAME  \
        --location=${REGION} \
        --destination-run-service=helloworld-events  \
        --destination-run-region=${REGION} \
        --event-filters="type=google.cloud.storage.object.v1.finalized" \
        --event-filters="bucket=PROJECT_ID-bucket" \
        --service-account=PROJECT_NUMBER-compute@developer.gserviceaccount.com

    取代:

    • TRIGGER_NAME 替換為觸發條件的名稱。
    • PROJECT_ID 改成您的 Google Cloud 專案 ID。
    • PROJECT_NUMBER 換成您的 Google Cloud 專案編號。

    請注意,在 Google Cloud 專案中首次建立 Eventarc 觸發條件時,Eventarc 服務代理程式可能會延遲佈建。您通常可以嘗試重新建立觸發條件來解決這個問題。詳情請參閱權限遭拒錯誤

  2. 確認觸發條件是否已成功建立。請注意,雖然觸發條件會立即建立,但觸發條件最多可能需要兩分鐘才能完全運作。

    gcloud eventarc triggers list --location=${REGION}

    畫面會顯示如下的輸出內容:

    NAME: helloworld-events
    TYPE: google.cloud.storage.object.v1.finalized
    DESTINATION: Cloud Run service: helloworld-events
    ACTIVE: Yes
    LOCATION: us-central1
    

產生及查看事件

將文字檔案上傳至 Cloud Storage 值區,產生並將事件路由至函式。Cloud Run 函式會在服務記錄中記錄事件。

  1. 將文字檔案上傳至 Cloud Storage,產生事件:

     echo "Hello World" > random.txt
     gcloud storage cp random.txt gs://PROJECT_ID-bucket/random.txt
    

    上傳作業會產生事件,而 Cloud Run 函式會記錄事件的訊息。

  2. 如要查看記錄項目,請按照下列步驟操作:

    1. 篩選記錄項目,並以 JSON 格式傳回輸出內容:

      gcloud logging read "resource.labels.service_name=helloworld-events AND textPayload:random.txt" --format=json
      
    2. 尋找類似下列內容的記錄項目:

      [
        {
         ....
          "resource": {
            "labels": {
              ....
              "location": "us-central1",
              .....
              "service_name": "helloworld-events"
            },
          },
          "textPayload": "File: random.txt",
           .....
        }
      ]
      

      記錄需要一些時間才會出現。如果沒有立即看到記錄,請稍候片刻再查看一次。

看到記錄項目後,即可確認您已成功部署事件驅動函式,並在文字檔案上傳至 Cloud Storage 時觸發該函式。

清除所用資源

如果您是為了這個教學課程建立新專案,請刪除專案。如果您使用現有的專案,且想保留該專案而不採用本教學課程中新增的變更,請刪除為教學課程建立的資源

刪除專案

如要避免付費,最簡單的方法就是刪除您為了本教學課程所建立的專案。

如要刪除專案:

  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 run services delete SERVICE_NAME

    其中 SERVICE_NAME 是您選擇的服務名稱。

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

  2. 移除您在教學課程設定期間新增的所有 gcloud CLI 預設設定。

    例如:

    gcloud config unset run/region

    gcloud config unset project

  3. 刪除本教學課程中建立的其他 Google Cloud 資源:

    • 刪除 Eventarc 觸發條件:
      gcloud eventarc triggers delete TRIGGER_NAME
      
      請將 TRIGGER_NAME 替換為觸發條件名稱。

後續步驟