他のワークフローを並列実行するワークフローを実行する


このチュートリアルでは、複数の子ワークフローを並行して実行する親ワークフローを作成して実行する方法を説明します。

次の図では、子ワークフローの 4 つの並列実行が呼び出されています。これにより、親ワークフローは並列ブランチでデータを処理でき、全体的な実行時間が短縮されます。親ワークフローは、すべての子ワークフローの実行が完了するのを待ってから、成功した実行と失敗した実行の概要を返し、エラー検出を簡素化します。

子ワークフローの並列反復処理を行う親ワークフロー

目標

このチュートリアルの内容は次のとおりです。

  1. 親ワークフローからデータを受け取る子ワークフローを作成してデプロイします。
  2. 並列 for ループを使用して複数の子ワークフローを実行する親ワークフローを作成してデプロイします。
  3. 子ワークフローの並列実行を呼び出す親ワークフローを実行します。
  4. 成功および失敗したすべての子ワークフローの実行結果が、マップに保存されて返されます。

Google Cloud コンソールで次のコマンドを実行するか、ターミナルまたは Cloud Shell で Google Cloud CLI を使用できます。

費用

このドキュメントでは、Google Cloud の次の課金対象のコンポーネントを使用します。

料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。 新しい Google Cloud ユーザーは無料トライアルをご利用いただける場合があります。

始める前に

組織で定義されているセキュリティの制約により、次の手順を完了できない場合があります。トラブルシューティング情報については、制約のある Google Cloud 環境でアプリケーションを開発するをご覧ください。

コンソール

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Workflow Executions and Workflows API を有効にします。

    API を有効にする

  5. Create a service account:

    1. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    2. Select your project.
    3. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

      In the Service account description field, enter a description. For example, Service account for quickstart.

    4. Click Create and continue.
    5. Grant the Workflows > Workflows Invoker role to the service account.

      To grant the role, find the Select a role list, then select Workflows > Workflows Invoker.

    6. Click Continue.
    7. Click Done to finish creating the service account.

  6. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  7. Google Cloud プロジェクトで課金が有効になっていることを確認します

  8. Workflow Executions and Workflows API を有効にします。

    API を有効にする

  9. Create a service account:

    1. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    2. Select your project.
    3. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

      In the Service account description field, enter a description. For example, Service account for quickstart.

    4. Click Create and continue.
    5. Grant the Workflows > Workflows Invoker role to the service account.

      To grant the role, find the Select a role list, then select Workflows > Workflows Invoker.

    6. Click Continue.
    7. Click Done to finish creating the service account.

gcloud

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Google Cloud CLI をインストールします。
  3. gcloud CLI を初期化するには:

    gcloud init
  4. Google Cloud プロジェクトを作成または選択します

    • Google Cloud プロジェクトを作成します。

      gcloud projects create PROJECT_ID

      PROJECT_ID は、作成する Google Cloud プロジェクトの名前に置き換えます。

    • 作成した Google Cloud プロジェクトを選択します。

      gcloud config set project PROJECT_ID

      PROJECT_ID は、実際の Google Cloud プロジェクト名に置き換えます。

  5. Google Cloud プロジェクトで課金が有効になっていることを確認します

  6. Workflow Executions and Workflows API を有効にします。

    gcloud services enable workflowexecutions.googleapis.comworkflows.googleapis.com
  7. Set up authentication:

    1. Create the service account:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      Replace SERVICE_ACCOUNT_NAME with a name for the service account.

    2. Grant the roles/workflows.invoker 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/workflows.invoker

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account
  8. Google Cloud CLI をインストールします。
  9. gcloud CLI を初期化するには:

    gcloud init
  10. Google Cloud プロジェクトを作成または選択します

    • Google Cloud プロジェクトを作成します。

      gcloud projects create PROJECT_ID

      PROJECT_ID は、作成する Google Cloud プロジェクトの名前に置き換えます。

    • 作成した Google Cloud プロジェクトを選択します。

      gcloud config set project PROJECT_ID

      PROJECT_ID は、実際の Google Cloud プロジェクト名に置き換えます。

  11. Google Cloud プロジェクトで課金が有効になっていることを確認します

  12. Workflow Executions and Workflows API を有効にします。

    gcloud services enable workflowexecutions.googleapis.comworkflows.googleapis.com
  13. Set up authentication:

    1. Create the service account:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      Replace SERVICE_ACCOUNT_NAME with a name for the service account.

    2. Grant the roles/workflows.invoker 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/workflows.invoker

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account

子ワークフローを作成してデプロイする

子ワークフローは、親ワークフローからデータを受け取って処理できます。子ワークフローは次のことを行います。

  • 引数として整数を受け取る
  • 一部の処理をシミュレートするために 10 秒間スリープします
  • ワークフローの実行の成功または失敗をシミュレートするインジケーター(整数が奇数か偶数かによる)を返します

コンソール

  1. Google Cloud コンソールの [ワークフロー] ページに移動します。

    [ワークフロー] に移動

  2. [ 作成] をクリックします。

  3. 新しいワークフローに workflow-child という名前を入力します。

  4. [リージョン] リストで [us-central1] を選択します。

  5. 先ほど作成したサービス アカウントを選択します。

  6. [Next(次へ)] をクリックします。

  7. ワークフロー エディタで、次のワークフローの定義を入力します。

    main:
      params: [args]
      steps:
        - init:
            assign:
              - iteration : ${args.iteration}
        - wait:
            call: sys.sleep
            args:
                seconds: 10
        - check_iteration_even_or_odd:
            switch:
              - condition: ${iteration % 2 == 0}
                next: raise_error
        - return_message:
            return: ${"Hello world"+iteration}
        - raise_error:
            raise: ${"Error with iteration "+iteration}
  8. [Deploy] をクリックします。

gcloud

  1. ワークフローのソースコード ファイルを作成します。

    touch workflow-child.yaml
    
  2. テキスト エディタでソースコード ファイルを開き、次のワークフローをファイルにコピーします。

    main:
      params: [args]
      steps:
        - init:
            assign:
              - iteration : ${args.iteration}
        - wait:
            call: sys.sleep
            args:
                seconds: 10
        - check_iteration_even_or_odd:
            switch:
              - condition: ${iteration % 2 == 0}
                next: raise_error
        - return_message:
            return: ${"Hello world"+iteration}
        - raise_error:
            raise: ${"Error with iteration "+iteration}
  3. ワークフローをデプロイします。

    gcloud workflows deploy workflow-child \
        --source=workflow-child.yaml \
        --location=us-central1 \
        --service-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com
    

    SERVICE_ACCOUNT_NAME は、先ほど作成したサービス アカウントの名前に置き換えます。

親ワークフローを作成してデプロイする

親ワークフローは、並列 for ループを使用して子ワークフローの複数のブランチを実行します。

  1. ワークフロー定義のソースコードをコピーします。次のパートで構成されています。

    1. マップは、子ワークフローの実行結果を保存するために使用されます。詳細については、マップをご覧ください。

      main:
        steps:
          - init:
              assign:
                - execution_results: {} # results from each execution
                - execution_results.success: {} # successful executions saved under 'success' key
                - execution_results.failure: {} # failed executions saved under 'failure' key
    2. for ループが並列実行され、子ワークフローが呼び出されます。詳細については、並列ステップイテレーションをご覧ください。

      - execute_child_workflows:
          parallel:
            shared: [execution_results]
            for:
              value: iteration
              in: [1, 2, 3, 4]
              steps:
                  - iterate:
    3. 子ワークフローは、コネクタを使用して呼び出されます。子ワークフローの各イテレーションには iteration 引数が渡されます。親ワークフローは、各子ワークフローの実行結果を待って保存します。詳細については、Workflows Executions API コネクタランタイム引数をご覧ください。

      try:
        steps:
          - execute_child_workflow:
              call: googleapis.workflowexecutions.v1.projects.locations.workflows.executions.run
              args:
                workflow_id: workflow-child
                #location: ...
                #project_id: ...
                argument:
                  iteration: ${iteration}
              result: execution_result
          - save_successful_execution:
              assign:
                - execution_results.success[string(iteration)]: ${execution_result}
      except:
          as: e
          steps:
            - save_failed_execution:
                assign:
                  - execution_results.failure[string(iteration)]: ${e}
    4. 実行結果が返されます。詳細については、ワークフローの実行を完了するをご覧ください。

      - return_execution_results:
          return: ${execution_results}
  2. ワークフローをデプロイします。

    コンソール

    1. Google Cloud コンソールの [ワークフロー] ページに移動します。

      [ワークフロー] に移動

    2. [ 作成] をクリックします。

    3. 新しいワークフローに workflow-parent という名前を入力します。

    4. [リージョン] リストで [us-central1] を選択します。

    5. 先ほど作成したサービス アカウントを選択します。

    6. [Next] をクリックします。

    7. ワークフロー エディタに、親ワークフローの定義を貼り付けます。

    8. [Deploy] をクリックします。

    gcloud

    1. ワークフローのソースコード ファイルを作成します。

      touch workflow-parent.yaml
      
    2. テキスト エディタでソースコード ファイルを開き、親ワークフローの定義を貼り付けます。

    3. ワークフローをデプロイします。

      gcloud workflows deploy workflow-parent \
          --source=workflow-parent.yaml \
          --location=us-central1 \
          --service-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com
      

      SERVICE_ACCOUNT_NAME は、先ほど作成したサービス アカウントの名前に置き換えます。

親ワークフローを実行する

子ワークフローの呼び出しが並行して実行されるように、親ワークフローを実行します。実行が完了するまでに約 10 秒かかります。

コンソール

  1. Google Cloud コンソールの [ワークフロー] ページに移動します。

    [ワークフロー] に移動

  2. [Workflows] ページで、[workflow-parent] ワークフローをクリックして詳細ページに移動します。

  3. [ワークフローの詳細] ページで [ 実行] を選択します。

  4. もう一度 [Execute] をクリックします。

  5. ワークフローの結果が [出力] ペインに表示されます。

    結果は次のようになります。イテレーション 2 と 4 でエラーが発生し、イテレーション 1 と 3 で成功しています。

    "failure": {
      "2": {
        "message": "Execution failed or cancelled.",
        "operation": {
          "argument": "{\"iteration\":2}",
          "duration": "10.157992541s",
          "endTime": "2023-07-11T13:13:13.028424329Z",
          "error": {
            "context": "RuntimeError: \"Error with iteration 2\"\nin step \"raise_error\", routine \"main\", line: 18",
            "payload": "\"Error with iteration 2\"",
    ...
      "4": {
        "message": "Execution failed or cancelled.",
        "operation": {
          "argument": "{\"iteration\":4}",
          "duration": "10.157929734s",
          "endTime": "2023-07-11T13:13:13.061289142Z",
          "error": {
            "context": "RuntimeError: \"Error with iteration 4\"\nin step \"raise_error\", routine \"main\", line: 18",
            "payload": "\"Error with iteration 4\"",
    ...
    "success": {
      "1": "Hello world1",
      "3": "Hello world3"

gcloud

ワークフローを実行します。

gcloud workflows run workflow-parent \
    --location=us-central1

結果は次のようになります。イテレーション 2 と 4 でエラーが発生し、イテレーション 1 と 3 で成功しています。

Waiting for execution [06c753e4-6947-4c62-ac0b-2a9d53fb1b8f] to complete...done.
argument: 'null'
duration: 14.065415004s
endTime: '2023-07-11T12:50:43.929023883Z'
name: projects/386837416586/locations/us-central1/workflows/workflow-parent/executions/06c753e4-6947-4c62-ac0b-2a9d53fb1b8f
result: '{"failure":{"2":{"message":"Execution failed or cancelled.","operation":{"argument":"{\"iteration\":2}","duration":"10.143718070s","endTime":"2023-07-11T12:50:40.673209821Z","error":{"context":"RuntimeError:
...
"Error with iteration 2\"\nin step \"raise_error\", routine \"main\", line: 18","payload":"\"Error
...
"Error with iteration 4\"\nin step \"raise_error\", routine \"main\", line: 18","payload":"\"Error
...
"success":{"1":"Hello world1","3":"Hello world3"}}'
startTime: '2023-07-11T12:50:29.863608879Z'
state: SUCCEEDED

子ワークフローを呼び出し、並列ブランチで子ワークフローの 4 回のイテレーションを実行し、子ワークフローの実行のたびに成功または失敗を示すワークフローが正常に作成され、デプロイされました。

クリーンアップ

このチュートリアル用に新規プロジェクトを作成した場合は、そのプロジェクトを削除します。既存のプロジェクトを使用し、このチュートリアルで変更を加えずに残す場合は、チュートリアル用に作成したリソースを削除します。

プロジェクトの削除

課金をなくす最も簡単な方法は、チュートリアル用に作成したプロジェクトを削除することです。

プロジェクトを削除するには:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

チュートリアル リソースの削除

このチュートリアルで作成したワークフローを削除します。

gcloud workflows delete workflow-child
gcloud workflows delete workflow-parent

次のステップ