本教程演示了如何通过将函数源代码 zip 文件上传到 Cloud Storage 存储桶来部署 HTTP 函数(使用 Terraform 预配资源)。Terraform 是一种开源工具,可让您通过声明式配置文件预配 Google Cloud 资源。
本教程以 Node.js HTTP 函数为例,但也适用于 Python、Go 和 Java HTTP 函数。 无论您使用哪种运行时,说明都是相同的。
目标
- 了解如何使用 Terraform 部署 HTTP 函数。
费用
在本文档中,您将使用 Google Cloud 的以下收费组件:
如需了解详情,请参阅 Cloud Functions 价格。
准备工作
- 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Cloud Functions, Cloud Run, Cloud Build, Artifact Registry, and Cloud Storage APIs.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Cloud Functions, Cloud Run, Cloud Build, Artifact Registry, and Cloud Storage APIs.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
准备开发环境。
如果您已经安装 gcloud CLI,请运行以下命令进行更新:
gcloud components update
设置您的环境
在本教程中,您将在 Cloud Shell 中运行命令。Cloud Shell 是一个已安装 Google Cloud CLI 的 shell 环境,其中包括 Google Cloud CLI 以及已为当前项目设置的值。Cloud Shell 可能需要几分钟才能完成初始化:
准备应用
在 Cloud Shell 中,执行以下步骤:
将示例应用代码库克隆到 Cloud Shell 实例:
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
切换到包含 Cloud Functions 函数示例代码的目录:
cd nodejs-docs-samples/functions/helloworld/helloworldHttp
本教程中使用的 Node.js 示例是一个基本的“Hello World”HTTP 函数。
创建一个包含 Terraform 将上传到 Cloud Storage 存储桶的函数源代码的 zip 文件:
zip -r function-source.zip .
请注意,该 zip 文件的根目录必须是函数源代码的根目录,因此上述命令包含
helloworldHttp
目录中的文件,但不包含目录本身。
创建 main.tf
文件
在
nodejs-docs-samples/functions/
目录中,为 Terraform 配置创建main.tf
文件:touch main.tf
将此 Terraform 配置复制到您的
main.tf
文件中:修改
main.tf
文件,确保它具有以下各项的正确值。每当配置更改(例如,要使用其他运行时或部署其他函数)时,您都需要修改此文件:- 运行时:在此示例中,运行时为
nodejs16
。 - 函数入口点:在此示例中,函数入口点为
helloHttp
。 - zip 文件的路径:在此示例中,如果将
main.tf
文件放在nodejs-docs-samples/functions/
目录中(如上所述),则路径为./helloworld/helloworldHttp/function-source.zip
。
- 运行时:在此示例中,运行时为
初始化 Terraform
在包含 main.tf
文件的 nodejs-docs-samples/functions/
目录中,运行以下命令以添加必要的插件并构建 .terraform
目录:
terraform init
应用 Terraform 配置
在包含 main.tf
文件的 nodejs-docs-samples/functions/
目录中,通过应用配置来部署函数。出现提示时,输入 yes
:
terraform apply
测试函数
当函数完成部署时,请记下 URI 特性,或使用以下命令查找该特性:
gcloud functions describe function-v2 --gen2 --region=us-central1 --format="value(serviceConfig.uri)"
向此网址发出请求,以查看函数的“Hello World”消息。请注意,部署的函数需要身份验证。因此,您必须在请求中提供凭据:
curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" YOUR_FUNCTION_URL
清理
完成本教程后,您可以删除自己创建的所有内容,以免产生任何额外费用。
凭借 Terraform,您可以通过在包含 main.tf
文件的 nodejs-docs-samples/functions/
目录中运行 terraform destroy
命令来移除配置文件中定义的所有资源:
terraform destroy
输入 yes
以允许 Terraform 删除您的资源。