通过创建总线和注册来发布和接收事件 (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. 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

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

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

  4. Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs.

    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. 在 Google Cloud 控制台中,激活 Cloud Shell。

    激活 Cloud Shell

    Cloud Shell 会话随即会在 Google Cloud 控制台的底部启动,并显示命令行提示符。Cloud Shell 是一个已安装 Google Cloud CLI 且已为当前项目设置值的 Shell 环境。该会话可能需要几秒钟时间来完成初始化。

  6. 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 资源启用应用 Terraform 配置所需的 API:

# 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_accountgoogle_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 显示“应用完成!”消息。

通过创建工作流将事件消息发布到总线

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. \
        --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 控制台中,前往管理资源页面。

    转到“管理资源”

  2. 在项目列表中,选择要删除的项目,然后点击删除
  3. 在对话框中输入项目 ID,然后点击关闭以删除项目。

后续步骤