本教程演示了如何通过将函数源代码 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.
您可使用价格计算器根据您的预计使用情况来估算费用。
准备工作
- 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.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions, Cloud Build, Artifact Registry, and Cloud Storage APIs.
-
Install the Google Cloud CLI.
-
如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
gcloud init
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions, Cloud Build, Artifact Registry, and Cloud Storage APIs.
-
Install the Google Cloud CLI.
-
如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
gcloud init
- 将
roles/run.invoker
和roles/cloudbuild.builds.builder
授予默认计算服务账号。 -
准备开发环境。
将示例应用代码库克隆到 Cloud Shell 实例:
git clone https://github.com/terraform-google-modules/terraform-docs-samples.git
切换到包含 Cloud Run functions 函数示例代码的目录:
cd terraform-docs-samples/functions/pubsub
本教程中使用的 Node.js 示例是一个基本的“Hello World”Pub/Sub 函数。 以下是
main.tf
文件:向主题发布消息(在此示例中,主题名称为
functions2-topic
):gcloud pubsub topics publish TOPIC_NAME --message="Friend"
读取函数日志以查看结果,其中
FUNCTION_NAME
是函数的名称(在此示例中,函数名称是function
):gcloud functions logs read FUNCTION_NAME
您应该会看到包含新的“Friend”消息的日志记录输出。
如果您已经安装 gcloud CLI,请运行以下命令进行更新:
gcloud components update
设置您的环境
在本教程中,您将在 Cloud Shell 中运行命令。Cloud Shell 是一个已安装 Google Cloud CLI 的 shell 环境,其中包括 Google Cloud CLI 以及已为当前项目设置的值。Cloud Shell 可能需要几分钟才能完成初始化:
准备应用
在 Cloud Shell 中,执行以下步骤:
初始化 Terraform
在包含 main.tf
文件的 terraform-docs-samples/functions/pubsub
目录中,运行以下命令以添加必要的插件并构建 .terraform
目录:
terraform init
验证 Terraform 配置
预览 Terraform 配置。这是可选步骤,但您可以验证 main.tf
的语法是否正确。此命令会显示将要创建的资源的预览:
terraform plan
应用 Terraform 配置
通过应用配置来部署函数。出现提示时,输入 yes
:
terraform apply
触发函数
如需测试 Pub/Sub 函数,请执行以下操作:
清理
完成本教程后,您可以删除自己创建的所有内容,以免产生任何额外费用。
Terraform 允许您通过运行 terraform destroy
命令来移除配置文件中定义的所有资源:
terraform destroy
输入 yes
以允许 Terraform 删除您的资源。