工作流示例

本页面提供了示例工作流定义,帮助您了解工作流语法及其常见使用模式。

身份验证

对于与其他 Google Cloud 资源通信的所有示例,您的工作流必须与拥有足够特权能够访问那些资源的服务帐号相关联。如需详细了解如何向服务帐号授予角色,请参阅授予、更改和撤消对资源的访问权限。如需了解如何更改与工作流关联的服务帐号,请参阅更新工作流。如需详细了解身份验证,请参阅在工作流中发出经过身份验证的请求

HTTP 请求

这些示例演示了如何发出 HTTP 请求。

发出外部 HTTP POST 请求

此示例向外部 HTTP 端点发出 POST 请求。

YAML

- getMessage:
    call: http.post
    args:
      url: https://www.example.com/endpoint
      body:
        someVal: "Hello World"
        anotherVal: 123
    result: theMessage
- returnValue:
    return: ${theMessage.body}

JSON

[
  {
    "getMessage": {
      "call": "http.post",
      "args": {
        "url": "https://www.example.com/endpoint",
        "body": {
          "someVal": "Hello World",
          "anotherVal": 123
        }
      },
      "result": "theMessage"
    }
  },
  {
    "returnValue": {
      "return": "${theMessage.body}"
    }
  }
]

使用标头发出外部 HTTP GET 请求

此示例使用自定义标头发出 HTTP GET 请求。此外,您还可以在发出其他类型的 HTTP 请求时提供自定义标头定义。

YAML

- getMessage:
    call: http.get
    args:
      url: https://www.example.com/endpoint
      headers:
        Content-Type: "text/plain"
      query:
        someVal: "Hello World"
        anotherVal: 123
    result: theMessage
- returnValue:
    return: ${theMessage.body}

JSON

[
  {
    "getMessage": {
      "call": "http.get",
      "args": {
        "url": "https://www.example.com/endpoint",
        "headers": {
          "Content-Type": "text/plain"
        },
        "query": {
          "someVal": "Hello World",
          "anotherVal": 123
        }
      },
      "result": "theMessage"
    }
  },
  {
    "returnValue": {
      "return": "${theMessage.body}"
    }
  }
]

变量、表达式和运行时参数

这些示例演示了如何为变量分配值、对表达式求值以及访问运行时参数。

分配变量

此示例为变量分配字符串值和数值。变量分配将按顺序执行。

YAML

- firstStep:
    assign:
      - SomeName: "Sherlock"
      - AnotherName: "Ada"
      - SomeIntegerNumber: 27
      - SomeDoubleNumber: 4.1

JSON

[
  {
    "firstStep": {
      "assign": [
        {
          "SomeName": "Sherlock"
        },
        {
          "AnotherName": "Ada"
        },
        {
          "SomeIntegerNumber": 27
        },
        {
          "SomeDoubleNumber": 4.1
        }
      ]
    }
  }
]

使用类型转换对表达式进行求值

此示例使用表达式分配变量值。FullName 变量使用上面定义的 LastName 变量。

YAML

- getMessage:
    assign:
      - name: "Harsha"
      - lastName: "Kapoor"
      - fullName: ${name+" "+lastName}
      - temperatureC: 27
      - temperatureF: ${temperatureC * 9/5 + 32}
      - temperatureMsg: ${"Current temperature is "+string(temperatureF)+" F"}
- returnValue:
    return: ${temperatureMsg}

JSON

[
  {
    "getMessage": {
      "assign": [
        {
          "name": "Harsha"
        },
        {
          "lastName": "Kapoor"
        },
        {
          "fullName": "${name+\" \"+lastName}"
        },
        {
          "temperatureC": 27
        },
        {
          "temperatureF": "${temperatureC * 9/5 + 32}"
        },
        {
          "temperatureMsg": "${\"Current temperature is \"+string(temperatureF)+\" F\"}"
        }
      ]
    }
  },
  {
    "returnValue": {
      "return": "${temperatureMsg}"
    }
  }
]

访问运行时参数

此示例会在执行请求的过程中访问传递给工作流的运行时参数。所有参数都存储在同一个字典中,声明为主工作流的参数。

运行此工作流时,请使用以下格式传入运行时参数:

{"firstName":"Sherlock", "lastName":"Holmes"}

YAML

main:
  params: [args]
  steps:
  - step1:
      assign:
        - outputVar: ${"Hello " + args.firstName + " " + args.lastName}
  - step2:
      return: ${outputVar}

JSON

{
  "main": {
    "params": [
      "args"
    ],
    "steps": [
      {
        "step1": {
          "assign": [
            {
              "outputVar": "${\"Hello \" + args.firstName + \" \" + args.lastName}"
            }
          ]
        }
      },
      {
        "step2": {
          "return": "${outputVar}"
        }
      }
    ]
  }
}

声明字典和数组

此示例同时定义了一个字典和几个数组。数组定义可使用方括号以内嵌方式提供,或作为列表提供(每行列出一项)。

YAML

- firstStep:
    assign:
      - myDictionary:
          name: Lila
          lastName: Barton
          birthYear: 1990
      - myArray1: [1, 2, 3]
      - myArray2:
          - 1
          - 2
          - 3
      - myArray3: ["Grzegorz", "Irina", "Yufei"]

JSON

[
  {
    "firstStep": {
      "assign": [
        {
          "myDictionary": {
            "name": "Lila",
            "lastName": "Barton",
            "birthYear": 1990
          }
        },
        {
          "myArray1": [
            1,
            2,
            3
          ]
        },
        {
          "myArray2": [
            1,
            2,
            3
          ]
        },
        {
          "myArray3": [
            "Grzegorz",
            "Irina",
            "Yufei"
          ]
        }
      ]
    }
  }
]

遍历数组

此示例会遍历字符串数组,并将它们串连在一起。您可以修改此工作流定义以处理其他数组。

YAML

- define:
    assign:
      - array: ["foo", "ba", "r"]
      - result: ""
      - i: 0
- check_condition:
    switch:
      - condition: ${len(array) > i}
        next: iterate
    next: exit_loop
- iterate:
    assign:
      - result: ${result + array[i]}
      - i: ${i+1}
    next: check_condition
- exit_loop:
    return:
        concat_result: ${result}

JSON

[
  {
    "define": {
      "assign": [
        {
          "array": [
            "foo",
            "ba",
            "r"
          ]
        },
        {
          "result": ""
        },
        {
          "i": 0
        }
      ]
    }
  },
  {
    "check_condition": {
      "switch": [
        {
          "condition": "${len(array) > i}",
          "next": "iterate"
        }
      ],
      "next": "exit_loop"
    }
  },
  {
    "iterate": {
      "assign": [
        {
          "result": "${result + array[i]}"
        },
        {
          "i": "${i+1}"
        }
      ],
      "next": "check_condition"
    }
  },
  {
    "exit_loop": {
      "return": {
        "concat_result": "${result}"
      }
    }
  }
]

步骤顺序

隐式步骤排序

此示例显示了工作流中的隐式步骤排序。默认情况下,系统会按照工作流在工作流定义中出现的顺序执行工作流的步骤。

YAML

- firstStep:
    call: http.get
    args:
      url: https://www.example.com/callA
- secondStep:
    call: http.get
    args:
      url: https://www.example.com/callB
- thirdStep:
    call: http.get
    args:
      url: https://www.example.com/callC

JSON

[
  {
    "firstStep": {
      "call": "http.get",
      "args": {
        "url": "https://www.example.com/callA"
      }
    }
  },
  {
    "secondStep": {
      "call": "http.get",
      "args": {
        "url": "https://www.example.com/callB"
      }
    }
  },
  {
    "thirdStep": {
      "call": "http.get",
      "args": {
        "url": "https://www.example.com/callC"
      }
    }
  }
]

使用跳转操作的显式步骤排序

此示例使用 next: 命令来明确定义工作流步骤的顺序。在此示例中,系统会按照与工作流定义中显示的顺序不同的顺序来执行步骤。

YAML

- firstStep:
    call: http.get
    args:
      url: https://www.somewhere.com/callA
    next: secondStep
- thirdStep:
    call: http.get
    args:
      url: https://www.somewhere.com/callB
    next: end
- secondStep:
    call: http.get
    args:
      url: https://www.somewhere.com/callC
    next: thirdStep

JSON

[
  {
    "firstStep": {
      "call": "http.get",
      "args": {
        "url": "https://www.somewhere.com/callA"
      },
      "next": "secondStep"
    }
  },
  {
    "thirdStep": {
      "call": "http.get",
      "args": {
        "url": "https://www.somewhere.com/callB"
      },
      "next": "end"
    }
  },
  {
    "secondStep": {
      "call": "http.get",
      "args": {
        "url": "https://www.somewhere.com/callC"
      },
      "next": "thirdStep"
    }
  }
]

如需详细了解如何使用 next 控制步骤顺序,请参阅控制工作流的执行顺序

条件跳转

在某些情况下,您可能希望工作流在满足条件时跳转到特定步骤。此示例将跳至步骤 smallmediumlarge,具体取决于工作流的第一步返回的值。

YAML

- firstStep:
    call: http.get
    args:
      url: https://www.example.com/callA
    result: firstResult
- whereToJump:
    switch:
      - condition: ${firstResult.body.SomeField < 10}
        next: small
      - condition: ${firstResult.body.SomeField < 100}
        next: medium
    next: large
- small:
    call: http.get
    args:
      url: https://www.example.com/SmallFunc
    next: end
- medium:
    call: http.get
    args:
      url: https://www.example.com/MediumFunc
    next: end
- large:
    call: http.get
    args:
      url: https://www.example.com/LargeFunc
    next: end

JSON

[
  {
    "firstStep": {
      "call": "http.get",
      "args": {
        "url": "https://www.example.com/callA"
      },
      "result": "firstResult"
    }
  },
  {
    "whereToJump": {
      "switch": [
        {
          "condition": "${firstResult.body.SomeField < 10}",
          "next": "small"
        },
        {
          "condition": "${firstResult.body.SomeField < 100}",
          "next": "medium"
        }
      ],
      "next": "large"
    }
  },
  {
    "small": {
      "call": "http.get",
      "args": {
        "url": "https://www.example.com/SmallFunc"
      },
      "next": "end"
    }
  },
  {
    "medium": {
      "call": "http.get",
      "args": {
        "url": "https://www.example.com/MediumFunc"
      },
      "next": "end"
    }
  },
  {
    "large": {
      "call": "http.get",
      "args": {
        "url": "https://www.example.com/LargeFunc"
      },
      "next": "end"
    }
  }
]

如需详细了解如何使用切换,请参阅条件跳转操作

采用嵌入的步骤切换结构

通过切换结构,还支持在满足某个条件时直接执行步骤,而无需跳转至其他步骤。这样做可减少工作流定义中的步骤数目,从而提升工作流的可读性。

YAML

- step1:
    assign:
      - a: 1
- step2:
    switch:
      - condition: ${a==1}
        steps:
          - stepA:
              assign:
                - a: ${a+7}
          - stepB:
              return: ${"increase a to:"+string(a)}
- step3:
    return: ${"default a="+string(a)}

JSON

[
  {
    "step1": {
      "assign": [
        {
          "a": 1
        }
      ]
    }
  },
  {
    "step2": {
      "switch": [
        {
          "condition": "${a==1}",
          "steps": [
            {
              "stepA": {
                "assign": [
                  {
                    "a": "${a+7}"
                  }
                ]
              }
            },
            {
              "stepB": {
                "return": "${\"increase a to:\"+string(a)}"
              }
            }
          ]
        }
      ]
    }
  },
  {
    "step3": {
      "return": "${\"default a=\"+string(a)}"
    }
  }
]

如需详细了解如何使用切换,请参阅条件跳转操作

简单的子工作流

此示例实现了一个简单的子工作流。如果工作流具有子工作流,则主工作流必须放在 main 块中。子工作流始终定义在工作流定义的正文之后。

YAML

main:
  steps:
    - first:
        call: hello
        args:
          input: "Kristof"
        result: someOutput
    - second:
        return: ${someOutput}

hello:
  params: [input]
  steps:
    - first:
        return: ${"Hello "+input}

JSON

{
  "main": {
    "steps": [
      {
        "first": {
          "call": "hello",
          "args": {
            "input": "Kristof"
          },
          "result": "someOutput"
        }
      },
      {
        "second": {
          "return": "${someOutput}"
        }
      }
    ]
  },
  "hello": {
    "params": [
      "input"
    ],
    "steps": [
      {
        "first": {
          "return": "${\"Hello \"+input}"
        }
      }
    ]
  }
}

如需详细了解如何使用子工作流,请参阅创建和使用子工作流

错误处理

这些示例说明了如何捕获异常和重试步骤。如需了解详情,请参阅语法参考页面的错误处理部分。

捕获和处理 HTTP 请求错误

此示例根据 GET 请求返回的 HTTP 状态代码实施自定义异常处理程序。工作流会捕获潜在异常并返回预定义的错误消息。如果未识别异常,则工作流执行将会失败,并抛出 GET 请求返回的异常。

同样的模式可用于捕获由 Cloud Run 或 Cloud Functions 工作负载引发的异常。

YAML

- readItem:
    try:
      call: http.get
      args:
        url: https://example.com/someapi
        auth:
          type: OIDC
      result: APIResponse
    except:
      as: e
      steps:
        - knownErrors:
            switch:
              - condition: ${not("HttpError" in e.tags)}
                next: connectionProblem
              - condition: ${e.code == 404}
                next: urlNotFound
              - condition: ${e.code == 403}
                next: authProblem
        - UnhandledException:
            raise: ${e}
- urlFound:
    return: ${APIResponse.body}
- connectionProblem:
    return: "Connection problem; check URL"
- urlNotFound:
    return: "Sorry, URL wasn't found"
- authProblem:
    return: "Authentication error"

JSON

[
  {
    "readItem": {
      "try": {
        "call": "http.get",
        "args": {
          "url": "https://example.com/someapi",
          "auth": {
            "type": "OIDC"
          }
        },
        "result": "APIResponse"
      },
      "except": {
        "as": "e",
        "steps": [
          {
            "knownErrors": {
              "switch": [
                {
                  "condition": "${not(\"HttpError\" in e.tags)}",
                  "next": "connectionProblem"
                },
                {
                  "condition": "${e.code == 404}",
                  "next": "urlNotFound"
                },
                {
                  "condition": "${e.code == 403}",
                  "next": "authProblem"
                }
              ]
            }
          },
          {
            "UnhandledException": {
              "raise": "${e}"
            }
          }
        ]
      }
    }
  },
  {
    "urlFound": {
      "return": "${APIResponse.body}"
    }
  },
  {
    "connectionProblem": {
      "return": "Connection problem; check URL"
    }
  },
  {
    "urlNotFound": {
      "return": "Sorry, URL wasn't found"
    }
  },
  {
    "authProblem": {
      "return": "Authentication error"
    }
  }
]

使用默认重试政策重试步骤

工作流附带内置的重试政策。此示例使用内置重试政策来处理 HTTP 请求。

使用自定义配置重试步骤

此示例使用自定义重试配置发出 HTTP 请求。此示例使用标准重试谓词,用于确定何时执行重试以及自定义的最大重试次数和退避参数。

YAML

- readItem:
    try:
      call: http.get
      args:
        url: https://example.com/someapi
      result: apiResponse
    retry:
      predicate: ${http.default_retry_predicate}
      max_retries: 5
      backoff:
        initial_delay: 2
        max_delay: 60
        multiplier: 2

JSON

[
  {
    "readItem": {
      "try": {
        "call": "http.get",
        "args": {
          "url": "https://example.com/someapi"
        },
        "result": "apiResponse"
      },
      "retry": {
        "predicate": "${http.default_retry_predicate}",
        "max_retries": 5,
        "backoff": {
          "initial_delay": 2,
          "max_delay": 60,
          "multiplier": 2
        }
      }
    }
  }
]

使用自定义谓词处理错误

本示例定义了自定义错误处理程序,包括自定义谓词和自定义退避参数。谓词定义为将单个参数作为字典的子工作流,用于保存异常定义。

YAML

main:
  steps:
    - readItem:
        try:
          call: http.get
          args:
            url: https://example.com/someapi
          result: apiResponse
        retry:
          predicate: ${myOwnPredicate}
          max_retries: 5
          backoff:
            initial_delay: 2
            max_delay: 60
            multiplier: 2
    - LastStep:
        return: "OK"

myOwnPredicate:
  params: [e]
  steps:
    - whatToRepeat:
        switch:
          - condition: "df"
            return: True
    - otherwise:
        return: False

JSON

{
  "main": {
    "steps": [
      {
        "readItem": {
          "try": {
            "call": "http.get",
            "args": {
              "url": "https://example.com/someapi"
            },
            "result": "apiResponse"
          },
          "retry": {
            "predicate": "${myOwnPredicate}",
            "max_retries": 5,
            "backoff": {
              "initial_delay": 2,
              "max_delay": 60,
              "multiplier": 2
            }
          }
        }
      },
      {
        "LastStep": {
          "return": "OK"
        }
      }
    ]
  },
  "myOwnPredicate": {
    "params": [
      "e"
    ],
    "steps": [
      {
        "whatToRepeat": {
          "switch": [
            {
              "condition": "df",
              "return": true
            }
          ]
        }
      },
      {
        "otherwise": {
          "return": false
        }
      }
    ]
  }
}

与其他 Google Cloud 服务关联

这些示例演示了工作流如何与其他 Google Cloud 服务进行交互。

使用身份验证向 Cloud Functions 函数发出 POST 请求

此示例向 Cloud Functions 函数发出 POST 请求,以仅接受经过身份验证的调用。

YAML

- callMyFunction:
    call: http.post
    args:
      url: https://us-central1-myproject123.cloudfunctions.net/myfunc1
      auth:
        type: OIDC
      body:
        someVal: "Hello World"
        anotherVal: 123
    result: theMessage
- returnValue:
    return: ${theMessage.body}

JSON

[
  {
    "callMyFunction": {
      "call": "http.post",
      "args": {
        "url": "https://us-central1-myproject123.cloudfunctions.net/myfunc1",
        "auth": {
          "type": "OIDC"
        },
        "body": {
          "someVal": "Hello World",
          "anotherVal": 123
        }
      },
      "result": "theMessage"
    }
  },
  {
    "returnValue": {
      "return": "${theMessage.body}"
    }
  }
]

如需详细了解如何向工作流中的资源进行身份验证,请参阅在工作流中发出经过身份验证的请求

使用身份验证向 Cloud Run 发出 GET 请求

此示例会调用需要进行身份验证的 Cloud Run 工作负载。

YAML

- callMyFunction:
    call: http.get
    args:
      url: https://example-12345-ew.a.run.app
      auth:
        type: OIDC
      query:
        someVal: "Hello World"
        anotherVal: 123
    result: theMessage
- returnValue:
    return: ${theMessage.body}

JSON

[
  {
    "callMyFunction": {
      "call": "http.get",
      "args": {
        "url": "https://example-12345-ew.a.run.app",
        "auth": {
          "type": "OIDC"
        },
        "query": {
          "someVal": "Hello World",
          "anotherVal": 123
        }
      },
      "result": "theMessage"
    }
  },
  {
    "returnValue": {
      "return": "${theMessage.body}"
    }
  }
]

如需详细了解如何向工作流中的资源进行身份验证,请参阅在工作流中发出经过身份验证的请求

停止 Compute Engine 虚拟机

此示例调用了 Compute Engine API 以停止虚拟机。项目 ID 是从内置环境变量中捕获的,它指向工作流所在的项目以帮助移植源代码。

工作流必须与具有足够特权能够停止虚拟机(例如具有 roles/compute.instanceAdmin.v1 角色)的服务帐号相关联。如需详细了解如何向服务帐号授予角色,请参阅授予、更改和撤消对资源的访问权限

YAML

- initialize:
    assign:
    - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_NUMBER")}
    - zone: "us-central1-a"
    - vmToStop: "examplevm"
- stopInstance:
    call: http.post
    args:
      url: ${"https://compute.googleapis.com/compute/v1/projects/"+project+"/zones/"+zone+"/instances/"+vmToStop+"/stop"}
      auth:
        type: OAuth2
    result: stopResult

JSON

[
  {
    "initialize": {
      "assign": [
        {
          "project": "${sys.get_env(\"GOOGLE_CLOUD_PROJECT_NUMBER\")}"
        },
        {
          "zone": "us-central1-a"
        },
        {
          "vmToStop": "examplevm"
        }
      ]
    }
  },
  {
    "stopInstance": {
      "call": "http.post",
      "args": {
        "url": "${\"https://compute.googleapis.com/compute/v1/projects/\"+project+\"/zones/\"+zone+\"/instances/\"+vmToStop+\"/stop\"}",
        "auth": {
          "type": "OAuth2"
        }
      },
      "result": "stopResult"
    }
  }
]

如需详细了解如何向工作流中的资源进行身份验证,请参阅在工作流中发出经过身份验证的请求

从 Firestore 读取数据

此示例展示了如何向 Firestore API 发出读取条目的请求。工作流会初始化变量,以在 initialize 步骤中设置项目的 ID、集合名称以及要检索的文档。

工作流必须与具有足够特权能够从 Firestore 读取数据(例如具有 roles/datastore.viewer 角色)的服务帐号相关联。如需详细了解如何向服务帐号授予角色,请参阅授予、更改和撤消对资源的访问权限

YAML

- initialize:
    assign:
    - project: "myproject123"
    - collection: "myEntries"
    - document: "Report"
- readItem:
    try:
      call: http.get
      args:
        url: ${"https://firestore.googleapis.com/v1/projects/"+project+"/databases/(default)/documents/"+collection+"/"+document}
        auth:
          type: OAuth2
      result: documentValue
    except:
      as: e
      steps:
      - isTheKeyFound:
          switch:
          - condition: ${e.code == 404}
            next: documentNotFound
          - condition: ${e.code == 403}
            next: authError
    next: documentFound
- documentNotFound:
    return: "Document not found."
- authError:
    return: "Authentication error."
- documentFound:
    return: ${documentValue.body.fields.LastName.stringValue}

JSON

[
  {
    "initialize": {
      "assign": [
        {
          "project": "myproject123"
        },
        {
          "collection": "myEntries"
        },
        {
          "document": "Report"
        }
      ]
    }
  },
  {
    "readItem": {
      "try": {
        "call": "http.get",
        "args": {
          "url": "${\"https://firestore.googleapis.com/v1/projects/\"+project+\"/databases/(default)/documents/\"+collection+\"/\"+document}",
          "auth": {
            "type": "OAuth2"
          }
        },
        "result": "documentValue"
      },
      "except": {
        "as": "e",
        "steps": [
          {
            "isTheKeyFound": {
              "switch": [
                {
                  "condition": "${e.code == 404}",
                  "next": "documentNotFound"
                },
                {
                  "condition": "${e.code == 403}",
                  "next": "authError"
                }
              ]
            }
          }
        ]
      },
      "next": "documentFound"
    }
  },
  {
    "documentNotFound": {
      "return": "Document not found."
    }
  },
  {
    "authError": {
      "return": "Authentication error."
    }
  },
  {
    "documentFound": {
      "return": "${documentValue.body.fields.LastName.stringValue}"
    }
  }
]

如需详细了解如何向工作流中的资源进行身份验证,请参阅在工作流中发出经过身份验证的请求

向 Firestore 写入数据

此示例向 Firestore API 发出写入条目的请求。工作流会初始化变量,以在 initialize 步骤中设置项目的 ID、集合名称以及要检索的文档。

工作流必须与具有足够特权能够从 Firestore 读取数据(例如具有 roles/datastore.user 角色)的服务帐号相关联。如需详细了解如何向服务帐号授予角色,请参阅授予、更改和撤消对资源的访问权限

YAML

- initialize:
    assign:
    - project: "myproject123"
    - collection: "myEntries"
    - document: "Visits"
- writeItem:
    call: http.request
    args:
      url: ${"https://firestore.googleapis.com/v1/projects/"+project+"/databases/(default)/documents/"+collection+"/"+document}
      auth:
        type: OAuth2
      method: PATCH
      body:
        name: ${"projects/"+project+"/databases/(default)/documents/"+collection+"/"+document}
        fields:
          Counter:
            integerValue: 7

JSON

[
  {
    "initialize": {
      "assign": [
        {
          "project": "myproject123"
        },
        {
          "collection": "myEntries"
        },
        {
          "document": "Visits"
        }
      ]
    }
  },
  {
    "writeItem": {
      "call": "http.request",
      "args": {
        "url": "${\"https://firestore.googleapis.com/v1/projects/\"+project+\"/databases/(default)/documents/\"+collection+\"/\"+document}",
        "auth": {
          "type": "OAuth2"
        },
        "method": "PATCH",
        "body": {
          "name": "${\"projects/\"+project+\"/databases/(default)/documents/\"+collection+\"/\"+document}",
          "fields": {
            "Counter": {
              "integerValue": 7
            }
          }
        }
      }
    }
  }
]

如需详细了解如何向工作流中的其他资源进行身份验证,请参阅在工作流中发出经过身份验证的请求

使用 Cloud Translation API 从英语翻译成俄语

此示例向 Cloud Translation API 发出将运行时参数字符串从英语翻译成俄语的请求。

工作流必须与具有足够特权能够向 Cloud Translation API 发送请求(例如具有 roles/cloudtranslate.user 角色)的服务帐号相关联。如需详细了解如何向服务帐号授予角色,请参阅授予、更改和撤消对资源的访问权限

运行此工作流时,请按以下格式传递运行时参数:

{"textToTranslate":"Hello world!"}

YAML

main:
  params: [args]
  steps:
    - newTranslation:
        call: http.post
        args:
          url: ${"https://translation.googleapis.com/v3/projects/"+sys.get_env("GOOGLE_CLOUD_PROJECT_NUMBER")+":translateText"}
          auth:
            type: OAuth2
          body:
            contents: ${args.textToTranslate}
            sourceLanguageCode: "en-US"
            targetLanguageCode: "ru-RU"
        result: translateResponse
    - assignTranslation:
        assign:
          - translationResult: ${translateResponse.body.translations[0].translatedText}
    - returnResult:
        return: ${translationResult}

JSON

{
  "main": {
    "params": [
      "args"
    ],
    "steps": [
      {
        "newTranslation": {
          "call": "http.post",
          "args": {
            "url": "${\"https://translation.googleapis.com/v3/projects/\"+sys.get_env(\"GOOGLE_CLOUD_PROJECT_NUMBER\")+\":translateText\"}",
            "auth": {
              "type": "OAuth2"
            },
            "body": {
              "contents": "${args.textToTranslate}",
              "sourceLanguageCode": "en-US",
              "targetLanguageCode": "ru-RU"
            }
          },
          "result": "translateResponse"
        }
      },
      {
        "assignTranslation": {
          "assign": [
            {
              "translationResult": "${translateResponse.body.translations[0].translatedText}"
            }
          ]
        }
      },
      {
        "returnResult": {
          "return": "${translationResult}"
        }
      }
    ]
  }
}

后续步骤