使用 gcloud CLI 建立工作流程

本快速入門導覽課程說明如何使用 Google Cloud CLI 建立、部署及執行您的第一項工作流程。範例工作流程會向公用 API 傳送要求,然後傳回 API 的回應。

如要查看所有 Workflows gcloud CLI 指令的清單,請參閱 Workflows gcloud CLI 參考頁面

事前準備

貴機構定義的安全性限制,可能會導致您無法完成下列步驟。如需疑難排解資訊,請參閱「在受限的 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. Install the Google Cloud CLI.

  3. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

  4. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  5. Create or select 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.
    • 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. 如要使用現有專案進行本指南中的操作,請確認您具有所需的權限。如果您建立新專案,則已具備必要權限。

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

  8. Enable the Workflows API:

    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.

    gcloud services enable workflows.googleapis.com
  9. Install the Google Cloud CLI.

  10. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

  11. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  12. Create or select 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.
    • 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.

  13. 如要使用現有專案進行本指南中的操作,請確認您具有所需的權限。如果您建立新專案,則已具備必要權限。

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

  15. Enable the Workflows API:

    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.

    gcloud services enable workflows.googleapis.com
  16. Set up authentication:

    1. Ensure that you have the Create Service Accounts IAM role (roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin). Learn how to grant roles.
    2. Create the service account:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      Replace SERVICE_ACCOUNT_NAME with a name for the service account.

    3. Grant the roles/logging.logWriter IAM role to the service account:

      gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=roles/logging.logWriter

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account
  17. 如要進一步瞭解服務帳戶角色和權限,請參閱授予工作流程存取Google Cloud 資源的權限

    必要的角色

    如要取得完成本快速入門導覽課程所需的權限,請要求管理員在專案中授予您下列 IAM 角色:

    如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

    您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

    建立、部署及執行工作流程

    1. 在主目錄中,建立名為 myFirstWorkflow.yamlmyFirstWorkflow.json 的新檔案。

    2. 複製以下工作流程並貼到新檔案中,然後儲存檔案:

      YAML

      main:
        params: [input]
        steps:
          - checkSearchTermInInput:
              switch:
                - condition: '${"searchTerm" in input}'
                  assign:
                    - searchTerm: '${input.searchTerm}'
                  next: readWikipedia
          - getLocation:
              call: sys.get_env
              args:
                name: GOOGLE_CLOUD_LOCATION
              result: location
          - setFromCallResult:
              assign:
                - searchTerm: '${text.split(location, "-")[0]}'
          - readWikipedia:
              call: http.get
              args:
                url: 'https://en.wikipedia.org/w/api.php'
                query:
                  action: opensearch
                  search: '${searchTerm}'
              result: wikiResult
          - returnOutput:
              return: '${wikiResult.body[1]}'

      JSON

      {
        "main": {
          "params": [
            "input"
          ],
          "steps": [
            {
              "checkSearchTermInInput": {
                "switch": [
                  {
                    "condition": "${\"searchTerm\" in input}",
                    "assign": [
                      {
                        "searchTerm": "${input.searchTerm}"
                      }
                    ],
                    "next": "readWikipedia"
                  }
                ]
              }
            },
            {
              "getLocation": {
                "call": "sys.get_env",
                "args": {
                  "name": "GOOGLE_CLOUD_LOCATION"
                },
                "result": "location"
              }
            },
            {
              "setFromCallResult": {
                "assign": [
                  {
                    "searchTerm": "${text.split(location, \"-\")[0]}"
                  }
                ]
              }
            },
            {
              "readWikipedia": {
                "call": "http.get",
                "args": {
                  "url": "https://en.wikipedia.org/w/api.php",
                  "query": {
                    "action": "opensearch",
                    "search": "${searchTerm}"
                  }
                },
                "result": "wikiResult"
              }
            },
            {
              "returnOutput": {
                "return": "${wikiResult.body[1]}"
              }
            }
          ]
        }
      }
      

      除非您自行輸入搜尋字詞,否則工作流程會使用您的Google Cloud 位置建構搜尋字詞,並將搜尋字詞傳送至 Wikipedia API。系統會傳回相關的維基百科文章清單。

    3. 部署工作流程,並與指定的服務帳戶建立關聯:

      gcloud workflows deploy myFirstWorkflow --source=myFirstWorkflow.EXTENSION \
          --service-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com
      

      更改下列內容:

      • EXTENSION:工作流程的副檔名;YAML 版本請使用 yaml,JSON 版本請使用 json
      • PROJECT_ID:專案 ID
    4. 執行工作流程:

      gcloud workflows run myFirstWorkflow \
          --data='SEARCH_TERM'
      

      SEARCH_TERM 替換為搜尋字詞,例如 {"searchTerm":"North"}。如果您輸入 {},系統會使用您的 Google Cloud位置建構搜尋字詞。

      這會傳回執行嘗試的結果。輸出結果會與下列內容相似:

      argument: '{"searchTerm":"North"}'
      duration: 0.210616856s
      endTime: '2023-05-10T21:56:39.465899376Z'
      name: projects/734581694262/locations/us-central1/workflows/workflow-1/executions/eae31f11-a5c3-47e2-8014-05b400820a79
      result: '["North","North America","Northern Ireland","North Korea","North Macedonia","North
        Carolina","Northrop Grumman B-2 Spirit","Northrop F-5","Northern Cyprus","North
        Dakota"]'
      startTime: '2023-05-10T21:56:39.255282520Z'
      state: SUCCEEDED
      status:
        currentSteps:
        - routine: main
          step: returnOutput
      workflowRevisionId: 000001-ac2
      

    您已部署並執行第一項工作流程!

    清除所用資源

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

    1. 刪除您建立的工作流程:

      gcloud workflows delete myFirstWorkflow
      
    2. 系統詢問您是否要繼續時,請輸入 y

    工作流程已刪除。

    後續步驟