Terraform 教學課程

本教學課程示範如何部署 HTTP 函式,方法為將函式原始碼 ZIP 檔案上傳至 Cloud Storage bucket,以及使用 Terraform 佈建資源。Terraform 是一項開放原始碼工具,可透過宣告式設定檔佈建 Google Cloud 資源。

本教學課程以 Node.js HTTP 函式為例,但也適用於 Python、Go 和 Java HTTP 函式。無論使用哪種執行階段,操作說明都相同。

使用 Terraform 部署時,必須將函式的原始碼 ZIP 檔案上傳至 Cloud Storage bucket (source_archive_bucket),並在 Terraform 設定中指定 Cloud Storage 物件名稱 (source_archive_object)。詳情請參閱 Terraform 規格指南

Cloud Run functions 會將您在 source_archive_bucket 上傳的原始碼檔案,複製到專案的 bucket。該 bucket 的名稱格式為 gcf-v2-sources-PROJECT_NUMBER-REGION (Cloud Run functions)gcf-sources-PROJECT_NUMBER-REGION (Cloud Run functions,第 1 代)。這項設定會因 CMEK 依附元件而異。

目標

  • 瞭解如何使用 Terraform 部署 HTTP 函式。

費用

在本文件中,您會使用下列 Google Cloud的計費元件:

For details, see Cloud Run functions pricing.

您可以使用 Pricing Calculator,根據預測用量估算費用。

初次使用 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.

    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

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

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

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    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.

    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

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

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

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    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. 準備開發環境。

    前往 Node.js 設定指南

  16. 必要的角色

    設定環境

    在本教學課程中,您將使用 Cloud Shell 執行指令。Cloud Shell 是已安裝 Google Cloud CLI (包括 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/basic

      本教學課程使用的 Node.js 範例,是基本的「Hello World」HTTP 函式。以下是 main.tf 檔案:

      terraform {
        required_providers {
          google = {
            source  = "hashicorp/google"
            version = ">= 4.34.0"
          }
        }
      }
      
      resource "random_id" "default" {
        byte_length = 8
      }
      
      resource "google_storage_bucket" "default" {
        name                        = "${random_id.default.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  = "functions/hello-world/"
      }
      resource "google_storage_bucket_object" "object" {
        name   = "function-source.zip"
        bucket = google_storage_bucket.default.name
        source = data.archive_file.default.output_path # Add path to the zipped function source code
      }
      
      resource "google_cloudfunctions2_function" "default" {
        name        = "function-v2"
        location    = "us-central1"
        description = "a new function"
      
        build_config {
          runtime     = "nodejs22"
          entry_point = "helloHttp" # Set the entry point
          source {
            storage_source {
              bucket = google_storage_bucket.default.name
              object = google_storage_bucket_object.object.name
            }
          }
        }
      
        service_config {
          max_instance_count = 1
          available_memory   = "256M"
          timeout_seconds    = 60
        }
      }
      
      resource "google_cloud_run_service_iam_member" "member" {
        location = google_cloudfunctions2_function.default.location
        service  = google_cloudfunctions2_function.default.name
        role     = "roles/run.invoker"
        member   = "allUsers"
      }
      
      output "function_uri" {
        value = google_cloudfunctions2_function.default.service_config[0].uri
      }

    初始化 Terraform

    在包含 main.tf 檔案的 terraform-docs-samples/functions/basic 目錄中執行下列指令,新增必要的外掛程式並建構 .terraform 目錄:

    terraform init
    

    套用 Terraform 設定

    在包含 main.tf 檔案的同一個 terraform-docs-samples/functions/basic 目錄中套用設定,即可部署函式。系統顯示提示時,請輸入 yes

    terraform apply
    

    測試函式

    1. 函式部署完畢後,請記下 URI 屬性,或使用下列指令找到該屬性:

      gcloud functions describe function-v2 --gen2 --region=us-central1 --format="value(serviceConfig.uri)"
      
    2. 對這個網址發出要求,即可看到函式的「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
    

    如要允許 Terraform 刪除資源,請輸入 yes