使用 Terraform 建立工作流程

本快速入門導覽課程說明如何使用 Terraform 建立、部署及執行您的第一項工作流程。Terraform 是一種基礎架構即程式碼工具,可讓您透過程式碼,以可預測的方式建立、變更及改善雲端基礎架構。瞭解如何使用 Terraform 在 Google Cloud上佈建基礎架構。

在本快速入門導覽課程中,範例工作流程會將要求傳送至公用 API,然後傳回 API 的回應。

您將完成下列事項:

  1. 使用 Terraform 啟用 Workflows API。
  2. 使用 Terraform 為工作流程建立服務帳戶。
  3. 使用 Terraform 定義及部署工作流程。
  4. 使用 Google Cloud CLI 執行工作流程。

事前準備

貴機構定義的安全性限制,可能會導致您無法完成下列步驟。如需疑難排解資訊,請參閱「在受限的 Google Cloud 環境中開發應用程式」。

請注意,Cloud Shell 已整合 Terraform。如需安裝 Terraform,請參閱 HashiCorp Terraform 說明文件

  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. Install the Google Cloud CLI.

  3. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  4. To initialize the gcloud CLI, run the following command:

    gcloud init
  5. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:

    gcloud services enable cloudresourcemanager.googleapis.com iam.googleapis.com
  8. Install the Google Cloud CLI.

  9. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  10. To initialize the gcloud CLI, run the following command:

    gcloud init
  11. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  12. Make sure that billing is enabled for your Google Cloud project.

  13. Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:

    gcloud services enable cloudresourcemanager.googleapis.com iam.googleapis.com

建立 Terraform 設定檔

建立名為 main.tf 的 Terraform 設定檔,並納入本快速入門中使用的 Terraform 適用的 Google 供應商資源。

請注意,您可以使用插補進行替換,例如參照變數、資源屬性和呼叫函式。

  1. 建立目錄:

    mkdir terraform
  2. 前往 terraform 目錄:

    cd terraform
  3. 在目錄中新增檔案 main.tf

    nano main.tf
  4. 將下列資源新增至 main.tf 檔案:

    1. 指派專案 ID:

      provider "google" {
      project = "PROJECT_ID"
      }

      PROJECT_ID 替換為專案 ID。

    2. 啟用 Workflows API:

      # Enable Workflows API
      resource "google_project_service" "default" {
        service            = "workflows.googleapis.com"
        disable_on_destroy = false
      }

    3. 為工作流程建立服務帳戶:

      # Create a dedicated service account
      resource "google_service_account" "default" {
        account_id   = "sample-workflows-sa"
        display_name = "Sample Workflows Service Account"
      }

    4. 使用 google_workflows_workflow 資源定義工作流程:

      # Create a workflow
      resource "google_workflows_workflow" "default" {
        name            = "sample-workflow"
        region          = "us-central1"
        description     = "A sample workflow"
        service_account = google_service_account.default.id
      
        deletion_protection = false # set to "true" in production
      
        labels = {
          env = "test"
        }
        user_env_vars = {
          url = "https://timeapi.io/api/Time/current/zone?timeZone=Europe/Amsterdam"
        }
        source_contents = <<-EOF
        # This is a sample workflow that you can replace with your source code
        #
        # The workflow does the following:
        # - Retrieves the current date from a public API and stores the
        #   response in `currentDate`
        # - Retrieves a list of Wikipedia articles from a public API related
        #   to the day of the week stored in `currentDate`
        # - Returns the list of articles in the workflow output
        #
        # Note that when you define workflows in Terraform, variables must be
        # escaped with two dollar signs ($$) and not a single sign ($)
      
        - getCurrentDate:
            call: http.get
            args:
                url: $${sys.get_env("url")}
            result: currentDate
        - readWikipedia:
            call: http.get
            args:
                url: https://en.wikipedia.org/w/api.php
                query:
                    action: opensearch
                    search: $${currentDate.body.dayOfWeek}
            result: wikiResult
        - returnOutput:
            return: $${wikiResult.body[1]}
      EOF
      
        depends_on = [google_project_service.default]
      }
      逸出。

範例工作流程會使用下列引數:

  • name:工作流程名稱。
  • region:工作流程的位置
  • description:工作流程說明。
  • service_account:與最新工作流程版本相關聯的服務帳戶電子郵件地址或專屬 ID。這個服務帳戶代表工作流程的身分,並決定工作流程擁有的權限。如果您在建立工作流程時未指定服務帳戶,工作流程會使用預設的 Compute Engine 服務帳戶做為身分。詳情請參閱「授予工作流程權限,以便存取 Google Cloud 資源」。
  • labels:要指派給這項工作流程的鍵/值標籤組合清單,可協助您整理 Google Cloud 例項。詳情請參閱「什麼是標籤?
  • user_env_vars:與這個工作流程修訂版本相關聯的使用者定義環境變數。詳情請參閱「使用環境變數」。
  • source_contents:要執行的 Workflows 程式碼。如要瞭解檔案大小限制,請參閱「資源限制」一節。

其他選用引數包括:

  • crypto_key_name:Cloud Key Management Service 金鑰的資源 ID,格式如下:

    projects/PROJECT_NAME/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME

    詳情請參閱「使用客戶管理的加密金鑰」。

  • call_log_level:在執行這項工作流程期間,要套用至呼叫和呼叫回應的記錄層級。可能的值包括:

    • CALL_LOG_LEVEL_UNSPECIFIED
    • LOG_ALL_CALLS
    • LOG_ERRORS_ONLY
    • LOG_NONE

    詳情請參閱「通話記錄」。

  • project:資源所屬專案的 ID。如未提供,則會使用供應商專案。

  • name_prefix:建立以指定前置字元開頭的專屬名稱。 如果未指定這個屬性和 name,系統會隨機選擇名稱值。

建立及執行工作流程

部署 Terraform 資源來建立工作流程,然後執行工作流程。

  1. 在目錄中初始化 Terraform:

    terraform init
  2. 確認您透過 Terraform 提議的變更符合預期計畫:

    terraform plan

    您可以忽略有關不使用 -out 選項的附註。

  3. 建立工作流程:

    terraform apply
  4. 在「Enter a value」(輸入值) 提示中輸入 yes,繼續建立資源。

  5. 確認工作流程已建立:

    gcloud workflows list --location us-central1

    畫面會顯示如下的輸出內容:

    NAME                                                                    STATE   REVISION_ID  UPDATE_TIME
    projects/project-name/locations/us-central1/workflows/sample-workflow   ACTIVE  000001-f9a   2024-02-24T13:38:58.353765906Z
  6. 您可以選擇執行工作流程:

    gcloud workflows execute sample-workflow

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本頁面所用資源的費用,請刪除含有這些資源的 Google Cloud 專案。

  1. 刪除您使用 Terraform 建立的所有資源:
    terraform destroy
  2. 刪除您建立的工作流程:
    gcloud workflows delete sample-workflow
    系統詢問是否要繼續時,請輸入 y
  3. 您也可以刪除專案,以免產生費用。 Google Cloud 刪除 Google Cloud 專案後,系統就會停止對專案使用的所有資源收取費用。

      Delete a Google Cloud project:

      gcloud projects delete PROJECT_ID

後續步驟