建立匯流排和註冊項目來發布及接收事件 (Terraform)

本快速入門導覽課程說明如何使用 Terraform,在 Google Cloud 專案中建立 Eventarc Advanced 匯流排並註冊,以便發布及接收事件訊息。

  • 匯流排可做為中央路由器,接收來自事件來源的訊息,或由提供者發布的訊息。

  • 註冊會透過處理管道,將匯流排收到的訊息轉送至一或多個目的地。

在本快速入門導覽課程中,您將:

  1. 將事件接收器服務部署至 Cloud Run。

  2. 建立 Eventarc Advanced 匯流排。

  3. 啟用 Google 來源事件。

  4. 建立 Eventarc Advanced 管道和註冊項目。

  5. 建立工作流程,將事件訊息發布至匯流排。

  6. 在 Cloud Run 記錄檔中查看事件資料。

您可以使用 Terraform 完成本快速入門的大部分步驟。如要使用 Google Cloud CLI 完成所有步驟,請參閱「從 Google 來源發布事件」。

如要進一步瞭解如何使用 Terraform,請參閱 Terraform on Google Cloud 說明文件。

事前準備

貴機構定義的安全性限制,可能會導致您無法完成下列步驟。如需疑難排解資訊,請參閱「在受限的 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. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

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

  5. Enable the Cloud Resource Manager and Identity and Access Management (IAM) 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

  6. 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

  7. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

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

  9. Enable the Cloud Resource Manager and Identity and Access Management (IAM) 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

  10. 在 Google Cloud 控制台中啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

  11. Terraform 已整合至 Cloud Shell 殼層環境,您可以使用 Cloud Shell 部署 Terraform 資源,不必安裝 Terraform。

必要的角色

如要取得完成本快速入門導覽課程所需的權限,請要求管理員在專案中授予您下列 IAM 角色:

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

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

準備部署 Terraform

部署任何 Terraform 資源前,您必須先建立 Terraform 設定檔。您可以使用 Terraform 語法,透過 Terraform 設定檔定義基礎架構的偏好最終狀態。

  1. 在 Cloud Shell 中,設定要套用 Terraform 設定的預設 Google Cloud 專案。每個專案只需要執行一次這個指令,而且可以在任何目錄中執行:

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    將 PROJECT_ID 替換為 Google Cloud 專案 ID。

    請注意,如果您在 Terraform 設定檔中設定明確值,環境變數就會遭到覆寫。

  2. 每個 Terraform 設定檔都必須有自己的目錄 (也稱為根模組)。在 Cloud Shell 中建立目錄,並在該目錄中建立新檔案:

    mkdir DIRECTORY && cd DIRECTORY && touch main.tf

    將 DIRECTORY 替換為 Terraform 目錄的名稱。

    檔案名稱必須有 .tf 副檔名,例如在本快速入門中,設定檔為 main.tf。

定義 Terraform 設定

將下列 Terraform 程式碼片段複製到 main.tf 檔案中。如要從 GitHub 複製整個程式碼範例,請在程式碼片段的右上角,按一下 >「在 GitHub 上查看」。

啟用 API

使用 google_project_service Terraform 資源啟用必要的 API,以便套用 Terraform 設定:

# Enable APIs
resource "google_project_service" "apis" {
  for_each = toset([
    "eventarc.googleapis.com",
    "eventarcpublishing.googleapis.com",
    "run.googleapis.com"
  ])
  service            = each.key
  disable_on_destroy = false
}

建立服務帳戶

如要進行測試,請建立專屬服務帳戶,並授予特定 IAM 角色。

使用 google_service_account 和 google_project_iam_member Terraform 資源建立服務帳戶,並授予發布及接收事件所需的角色:

# Used to retrieve project information later
data "google_project" "project" {}

# Create a dedicated service account
resource "google_service_account" "default" {
  account_id   = "eventarc-advanced-sa"
  display_name = "Eventarc Advanced quickstart service account"
}

# Grant permission to receive Eventarc events
resource "google_project_iam_member" "eventreceiver" {
  project = data.google_project.project.id
  role    = "roles/eventarc.eventReceiver"
  member  = "serviceAccount:${google_service_account.default.email}"
}

# Grant permission to invoke Cloud Run services
resource "google_project_iam_member" "runinvoker" {
  project = data.google_project.project.id
  role    = "roles/run.invoker"
  member  = "serviceAccount:${google_service_account.default.email}"
}

建立事件目的地

使用 google_cloud_run_v2_service Terraform 資源建立 Cloud Run 服務,做為記錄事件內容的事件目的地:

# Deploy Cloud Run service
resource "google_cloud_run_v2_service" "default" {
  name     = "example-service"
  location = "us-central1"

  deletion_protection = false # set to "true" in production

  template {
    containers {
      # This sample container listens to HTTP requests and logs received events
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
    service_account = google_service_account.default.email
  }

  depends_on = [google_project_service.apis]
}

建立 Eventarc Advanced 匯流排

匯流排會接收來自訊息來源或供應商發布的事件訊息,並做為訊息路由器。詳情請參閱「建立用於傳送訊息的匯流排」。

使用 google_eventarc_message_bus Terraform 資源建立 Eventarc Advanced 匯流排:

# Create an Eventarc Advanced bus
resource "google_eventarc_message_bus" "default" {
  location       = "us-central1"
  message_bus_id = "example-bus"
}

啟用 Google 來源相關事件

如要發布 Google 來源的事件,您必須建立 GoogleApiSource 資源,代表訂閱特定 Eventarc Advanced 匯流排的 Google API 事件。詳情請參閱「發布 Google 來源的事件」。

使用 google_eventarc_google_api_source Terraform 資源,啟用 Google 來源的事件:

# Enable events from Google API sources
resource "google_eventarc_google_api_source" "default" {
  location             = "us-central1"
  google_api_source_id = "example-google-api-source"
  destination          = google_eventarc_message_bus.default.id
}

系統現在會收集並發布直接從 Google 來源傳送至匯流排的所有支援 Google 的活動類型。

建立 Eventarc Advanced 管道

您可以設定目標目的地,並選擇是否先轉換相符的事件,再傳送至目的地。

使用 google_eventarc_pipeline Terraform 資源建立管道:

# Create an Eventarc Advanced pipeline
resource "google_eventarc_pipeline" "default" {
  location    = "us-central1"
  pipeline_id = "example-pipeline"
  destinations {
    http_endpoint {
      uri = google_cloud_run_v2_service.default.uri
    }
    authentication_config {
      google_oidc {
        service_account = google_service_account.default.email
      }
    }
  }
}

事件目的地是 Cloud Run 服務的完整網址,例如 https://SERVICE_NAME-abcdef-uc.a.run.app。服務帳戶電子郵件地址用於產生 OIDC 權杖。

建立 Eventarc Advanced 註冊項目

註冊項目會決定要將哪些訊息轉送至目的地,並指定用於設定事件訊息目的地的管道。詳情請參閱「建立註冊項目以接收事件」。

使用 google_eventarc_enrollment Terraform 資源建立註冊項目:

# Create an Eventarc Advanced enrollment
resource "google_eventarc_enrollment" "default" {
  location      = "us-central1"
  enrollment_id = "example-enrollment"
  message_bus   = google_eventarc_message_bus.default.id
  destination   = google_eventarc_pipeline.default.id
  cel_match     = "message.type == 'google.cloud.workflows.workflow.v1.created'"
}

註冊的相符運算式使用一般運算語言 (CEL),在工作流程建立時發布事件訊息。在後續步驟中,您將建立工作流程。

套用 Terraform 設定

使用 Terraform CLI 根據設定檔佈建基礎架構。詳情請參閱「基本 Terraform 指令」。

  1. 初始化 Terraform。每個目錄只需執行一次這項操作。

    terraform init

    如要使用最新版 Google 供應商,請加入 -upgrade 選項:

    terraform init -upgrade
  2. 檢查設定,確認 Terraform 將建立或更新的資源符合您的預期:

    terraform plan

    視需要修正設定。

  3. 執行下列指令,並在提示中輸入 yes,即可套用 Terraform 設定:

    terraform apply

    一般而言,您會一次套用所有設定。不過,您也可以指定特定資源。例如:

    terraform apply -target="google_eventarc_message_bus.default"

    等待 Terraform 顯示「Apply complete!」訊息。

建立工作流程,將事件訊息發布至匯流排

Workflows 是全代管的自動化調度管理平台,可按照您定義的順序執行服務,也就是工作流程。建立工作流程,從 Google 來源產生支援的事件類型。

  1. 在主目錄中,建立名為 myWorkflow.yaml 的新檔案。

  2. 複製以下工作流程並貼到新檔案中,然後儲存檔案:

    main:
        params: [input]
        steps:
        - checkSearchTermInInput:
            switch:
                - condition: '${"searchTerm" in input}'
                  assign:
                    - searchTerm: '${input.searchTerm}'
                  next: readWikipedia
        - getLocation:
            call: sys.get_env
            args:
                name: GOOGLE_CLOUD_LOCATION
            result: location
        - setFromCallResult:
            assign:
                - searchTerm: '${text.split(location, "-")[0]}'
        - readWikipedia:
            call: http.get
            args:
                url: 'https://en.wikipedia.org/w/api.php'
                query:
                    action: opensearch
                    search: '${searchTerm}'
            result: wikiResult
        - returnOutput:
                return: '${wikiResult.body[1]}'
    

    這個工作流程會將工作流程部署的區域傳遞至 Wikipedia API,並傳回相關 Wikipedia 文章的清單。

  3. 使用 gcloud workflows deploy 指令部署工作流程:

    gcloud workflows deploy example-workflow --source=myWorkflow.yaml \
        --service-account=eventarc-advanced-sa@PROJECT_ID.iam.gserviceaccount.com \
        --location=us-central1

在 Cloud Run 記錄中查看事件資料

將事件發布至 Eventarc Advanced 匯流排後,您可以查看 Cloud Run 服務的記錄,確認事件是否如預期收到。

  1. 篩選服務建立的記錄項目:

    gcloud logging read 'jsonPayload.message: "Received event of type google.cloud.workflows.workflow.v1.created."'
    
  2. 尋找類似下列內容的記錄項目:

    message: 'Received event of type google.cloud.workflows.workflow.v1.created.
    Event data: {"@type":"type.googleapis.com/google.events.cloud.workflows.v1.WorkflowEventData","payload":{"name":"projects/PROJECT_ID/locations/us-central1/workflows/example-workflow","state":"ACTIVE"...
    

您已成功建立 Eventarc Advanced 匯流排和註冊項目、啟用發布來自 Google 來源的事件、建立工作流程以從 Google 供應商產生支援的事件類型,然後在事件接收器服務的記錄中驗證預期結果。

清除所用資源

執行下列指令,並在提示中輸入 yes,即可移除先前透過 Terraform 設定套用的資源:

terraform destroy

您也可以刪除 Google Cloud 專案,以免產生費用。刪除 Google Cloud 專案後,系統就會停止對該專案中使用的所有資源計費。

  1. 前往 Google Cloud 控制台的「Manage resources」(管理資源) 頁面。

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

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

後續步驟