使用 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。系统会返回相关 Wikipedia 文章的列表。

    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

    工作流已删除。

    后续步骤