本教程演示了如何通过将函数源代码 zip 文件上传到 Cloud Storage 存储桶来部署 HTTP 函数(使用 Terraform 预配资源)。Terraform 是一种开源工具,可让您通过声明式配置文件预配 Google Cloud 资源。
本教程以 Node.js HTTP 函数为例,但也适用于 Python、Go 和 Java HTTP 函数。无论您使用哪种运行时,说明都是相同的。
目标
- 了解如何使用 Terraform 部署 HTTP 函数。
费用
在本文档中,您将使用 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.
-
Make sure that billing is enabled for your 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.
-
Make sure that billing is enabled for your 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/terraform-google-modules/terraform-docs-samples.git
切换到包含 Cloud Run functions 示例代码的目录:
cd terraform-docs-samples/functions/basic
本教程中使用的 Node.js 示例是一个基本的“Hello World”HTTP 函数。下面是
main.tf
文件:
初始化 Terraform
在包含 main.tf
文件的 terraform-docs-samples/functions/basic
目录中,运行以下命令以添加必要的插件并构建 .terraform
目录:
terraform init
应用 Terraform 配置
在包含 main.tf
文件的同一 terraform-docs-samples/functions/basic
目录中,通过应用配置来部署函数。出现提示时,输入 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
文件的 terraform-docs-samples/functions/basic
目录中运行 terraform destroy
命令来移除配置文件中定义的所有资源:
terraform destroy
输入 yes
以允许 Terraform 删除您的资源。