다른 워크플로를 동시에 실행하는 워크플로 실행


이 튜토리얼에서는 여러 하위 워크플로를 동시에 실행하는 상위 워크플로를 만들고 실행하는 방법을 보여줍니다.

다음 다이어그램에서는 하위 워크플로가 동시에 4번 실행되도록 호출됩니다. 이렇게 하면 상위 워크플로가 병렬 분기로 데이터를 처리할 수 있고 전체 실행 시간이 줄어듭니다. 상위 워크플로는 성공 및 실패한 실행에 대한 요약을 반환하기 전에 모든 하위 워크플로 실행이 완료될 때까지 기다려서 오류 감지를 간소화합니다.

하위 워크플로의 동시 반복을 호출하는 상위 워크플로

목표

이 튜토리얼에서는 다음 단계를 진행합니다.

  1. 상위 워크플로에서 데이터를 수신하는 하위 워크플로를 만들고 배포합니다.
  2. 병렬 for 루프를 사용해서 여러 하위 워크플로를 실행하는 상위 워크플로를 만들고 배포합니다.
  3. 하위 워크플로의 병렬 실행을 호출하는 상위 워크플로를 실행합니다.
  4. 성공 및 실패한 모든 하위 워크플로 실행의 결과가 저장되고 맵에 반환됩니다.

Google Cloud 콘솔에서 또는 터미널이나 Cloud Shell에서 Google Cloud CLI를 사용하여 다음 명령어를 실행할 수 있습니다.

비용

이 문서에서는 비용이 청구될 수 있는 다음과 같은 Google Cloud 구성요소를 사용합니다.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용하세요. Google Cloud를 처음 사용하는 사용자는 무료 체험판을 사용할 수 있습니다.

시작하기 전에

조직에서 정의한 보안 제약조건으로 인해 다음 단계를 완료하지 못할 수 있습니다. 문제 해결 정보는 제한된 Google Cloud 환경에서 애플리케이션 개발을 참조하세요.

콘솔

  1. Google 계정에 로그인합니다.

    아직 계정이 없으면 새 계정을 등록하세요.

  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. API Workflow Executions and Workflows 사용 설정

    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. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  7. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  8. API Workflow Executions and Workflows 사용 설정

    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. Google 계정에 로그인합니다.

    아직 계정이 없으면 새 계정을 등록하세요.

  2. Google Cloud CLI를 설치합니다.
  3. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  4. 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.

  5. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  6. Workflow Executions and Workflows API를 사용 설정합니다.

    gcloud services enable workflowexecutions.googleapis.com workflows.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. 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.

  11. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  12. Workflow Executions and Workflows API를 사용 설정합니다.

    gcloud services enable workflowexecutions.googleapis.com workflows.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 콘솔에서 Workflows 페이지로 이동합니다.

    Workflows로 이동

  2. 만들기를 클릭합니다.

  3. 새 워크플로에 대해 workflow-child 이름을 입력합니다.

  4. 리전 목록에서 us-central1을 선택합니다.

  5. 이전에 만든 서비스 계정을 선택합니다.

  6. 다음을 클릭합니다.

  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. 배포를 클릭합니다.

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 콘솔에서 Workflows 페이지로 이동합니다.

      Workflows로 이동

    2. 만들기를 클릭합니다.

    3. 새 워크플로에 대해 workflow-parent 이름을 입력합니다.

    4. 리전 목록에서 us-central1을 선택합니다.

    5. 이전에 만든 서비스 계정을 선택합니다.

    6. 다음을 클릭합니다.

    7. 워크플로 편집기에서 상위 워크플로의 정의를 붙여넣습니다.

    8. 배포를 클릭합니다.

    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 콘솔에서 Workflows 페이지로 이동합니다.

    Workflows로 이동

  2. Workflows 페이지에서 workflow-parent 워크플로를 클릭하여 세부정보 페이지로 이동합니다.

  3. Workflows 세부정보 페이지에서 실행을 클릭합니다.

  4. 실행을 다시 클릭합니다.

  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. Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.

튜토리얼 리소스 삭제

이 튜토리얼에서 만든 워크플로를 삭제하세요.

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

다음 단계