Terraform Pub/Sub 教程


本教程演示了如何通过将函数源代码 zip 文件上传到 Cloud Storage 存储桶来部署 Pub/Sub 函数(使用 Terraform 预配资源)。Terraform 是一种开源工具,可让您通过声明式配置文件预配 Google Cloud 资源。

本教程以 Node.js 函数为例,但也适用于 Python、Go 和 Java 函数。 无论您使用哪种运行时,说明都是相同的。 如需详细了解如何将 Terraform 与 Cloud Functions v2 API 搭配使用,请参阅 Hashicorp 的参考文档页面

目标

  • 了解如何使用 Terraform 部署 Pub/Sub 函数。

费用

在本文档中,您将使用 Google Cloud的以下收费组件:

For details, see Cloud Run functions pricing.

您可使用价格计算器根据您的预计使用情况来估算费用。

新 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. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions, Cloud Build, Artifact Registry, and Cloud Storage APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. 如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI

  7. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

  10. Enable the Cloud Functions, Cloud Build, Artifact Registry, and Cloud Storage APIs.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. 如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI

  13. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  14. 如果您已经安装 gcloud CLI,请运行以下命令进行更新:

    gcloud components update
  15. roles/run.invokerroles/cloudbuild.builds.builder 授予默认计算服务账号。
  16. 准备开发环境。

    转到 Node.js 设置指南

  17. 设置您的环境

    在本教程中,您将在 Cloud Shell 中运行命令。Cloud Shell 是一个已安装 Google Cloud CLI 的 shell 环境,其中包括 Google Cloud CLI 以及已为当前项目设置的值。Cloud Shell 可能需要几分钟才能完成初始化:

    打开 Cloud Shell

    准备应用

    在 Cloud Shell 中,执行以下步骤:

    1. 将示例应用代码库克隆到 Cloud Shell 实例:

      git clone https://github.com/terraform-google-modules/terraform-docs-samples.git
    2. 切换到包含 Cloud Run functions 函数示例代码的目录:

      cd terraform-docs-samples/functions/pubsub

      本教程中使用的 Node.js 示例是一个基本的“Hello World”Pub/Sub 函数。 以下是 main.tf 文件:

      terraform {
        required_providers {
          google = {
            source  = "hashicorp/google"
            version = ">= 4.34.0"
          }
        }
      }
      
      resource "random_id" "bucket_prefix" {
        byte_length = 8
      }
      
      
      resource "google_service_account" "default" {
        account_id   = "test-gcf-sa"
        display_name = "Test Service Account"
      }
      
      resource "google_pubsub_topic" "default" {
        name = "functions2-topic"
      }
      
      resource "google_storage_bucket" "default" {
        name                        = "${random_id.bucket_prefix.hex}-gcf-source" # Every bucket name must be globally unique
        location                    = "US"
        uniform_bucket_level_access = true
      }
      
      data "archive_file" "default" {
        type        = "zip"
        output_path = "/tmp/function-source.zip"
        source_dir  = "function-source/"
      }
      
      resource "google_storage_bucket_object" "default" {
        name   = "function-source.zip"
        bucket = google_storage_bucket.default.name
        source = data.archive_file.default.output_path # Path to the zipped function source code
      }
      
      resource "google_cloudfunctions2_function" "default" {
        name        = "function"
        location    = "us-central1"
        description = "a new function"
      
        build_config {
          runtime     = "nodejs22"
          entry_point = "helloPubSub" # Set the entry point
          environment_variables = {
            BUILD_CONFIG_TEST = "build_test"
          }
          source {
            storage_source {
              bucket = google_storage_bucket.default.name
              object = google_storage_bucket_object.default.name
            }
          }
        }
      
        service_config {
          max_instance_count = 3
          min_instance_count = 1
          available_memory   = "256M"
          timeout_seconds    = 60
          environment_variables = {
            SERVICE_CONFIG_TEST = "config_test"
          }
          ingress_settings               = "ALLOW_INTERNAL_ONLY"
          all_traffic_on_latest_revision = true
          service_account_email          = google_service_account.default.email
        }
      
        event_trigger {
          trigger_region = "us-central1"
          event_type     = "google.cloud.pubsub.topic.v1.messagePublished"
          pubsub_topic   = google_pubsub_topic.default.id
          retry_policy   = "RETRY_POLICY_RETRY"
        }
      }

    初始化 Terraform

    在包含 main.tf 文件的 terraform-docs-samples/functions/pubsub 目录中,运行以下命令以添加必要的插件并构建 .terraform 目录:

    terraform init
    

    验证 Terraform 配置

    预览 Terraform 配置。这是可选步骤,但您可以验证 main.tf 的语法是否正确。此命令会显示将要创建的资源的预览:

    terraform plan
    

    应用 Terraform 配置

    通过应用配置来部署函数。出现提示时,输入 yes

    terraform apply
    

    触发函数

    如需测试 Pub/Sub 函数,请执行以下操作:

    1. 向主题发布消息(在此示例中,主题名称为 functions2-topic):

      gcloud pubsub topics publish TOPIC_NAME --message="Friend"
    2. 读取函数日志以查看结果,其中 FUNCTION_NAME 是函数的名称(在此示例中,函数名称是 function):

      gcloud functions logs read FUNCTION_NAME

      您应该会看到包含新的“Friend”消息的日志记录输出。

    清理

    完成本教程后,您可以删除自己创建的所有内容,以免产生任何额外费用。

    Terraform 允许您通过运行 terraform destroy 命令来移除配置文件中定义的所有资源:

    terraform destroy
    

    输入 yes 以允许 Terraform 删除您的资源。