Cloud 클라이언트 라이브러리를 사용하여 워크플로 실행

이 빠른 시작에서는 Cloud 클라이언트 라이브러리를 사용하여 워크플로를 실행하고 실행 결과를 확인하는 방법을 보여줍니다.

Cloud 클라이언트 라이브러리 설치 및 개발 환경 설정에 대한 자세한 내용은 Workflows 클라이언트 라이브러리 개요를 참고하세요.

터미널 또는 Cloud Shell에서 Google Cloud CLI를 사용하여 다음 단계를 완료할 수 있습니다.

시작하기 전에

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

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud CLI를 설치합니다.

  3. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  4. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init
  5. Google Cloud 프로젝트를 만들거나 선택합니다.

    프로젝트를 선택하거나 만드는 데 필요한 역할

    • 프로젝트 선택: 프로젝트를 선택하는 데는 특정 IAM 역할이 필요하지 않습니다. 역할이 부여된 프로젝트를 선택하면 됩니다.
    • 프로젝트 만들기: 프로젝트를 만들려면 resourcemanager.projects.create 권한이 포함된 프로젝트 생성자 역할(roles/resourcemanager.projectCreator)이 필요합니다. 역할 부여 방법 알아보기
    • Google Cloud 프로젝트를 만듭니다.

      gcloud projects create PROJECT_ID

      PROJECT_ID를 만들려는 Google Cloud 프로젝트의 이름으로 바꿉니다.

    • 만든 Google Cloud 프로젝트를 선택합니다.

      gcloud config set project PROJECT_ID

      PROJECT_ID을 Google Cloud 프로젝트 이름으로 바꿉니다.

  6. 이 가이드에 기존 프로젝트를 사용하는 경우 이 가이드를 완료하는 데 필요한 권한이 있는지 확인합니다. 새 프로젝트를 만든 경우에는 이미 필요한 권한이 있습니다.

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

  8. Workflows API를 사용 설정합니다.

    API 사용 설정에 필요한 역할

    API를 사용 설정하려면 serviceusage.services.enable 권한이 필요합니다. 프로젝트를 만든 경우 소유자 역할 (roles/owner)을 통해 이 권한이 이미 있을 수 있습니다. 그렇지 않으면 서비스 사용량 관리자 역할 (roles/serviceusage.serviceUsageAdmin)을 통해 이 권한을 얻을 수 있습니다. 역할을 부여하는 방법 알아보기

    gcloud services enable workflows.googleapis.com
  9. Google Cloud CLI를 설치합니다.

  10. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  11. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init
  12. Google Cloud 프로젝트를 만들거나 선택합니다.

    프로젝트를 선택하거나 만드는 데 필요한 역할

    • 프로젝트 선택: 프로젝트를 선택하는 데는 특정 IAM 역할이 필요하지 않습니다. 역할이 부여된 프로젝트를 선택하면 됩니다.
    • 프로젝트 만들기: 프로젝트를 만들려면 resourcemanager.projects.create 권한이 포함된 프로젝트 생성자 역할(roles/resourcemanager.projectCreator)이 필요합니다. 역할 부여 방법 알아보기
    • Google Cloud 프로젝트를 만듭니다.

      gcloud projects create PROJECT_ID

      PROJECT_ID를 만들려는 Google Cloud 프로젝트의 이름으로 바꿉니다.

    • 만든 Google Cloud 프로젝트를 선택합니다.

      gcloud config set project PROJECT_ID

      PROJECT_ID을 Google Cloud 프로젝트 이름으로 바꿉니다.

  13. 이 가이드에 기존 프로젝트를 사용하는 경우 이 가이드를 완료하는 데 필요한 권한이 있는지 확인합니다. 새 프로젝트를 만든 경우에는 이미 필요한 권한이 있습니다.

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

  15. Workflows API를 사용 설정합니다.

    API 사용 설정에 필요한 역할

    API를 사용 설정하려면 serviceusage.services.enable 권한이 필요합니다. 프로젝트를 만든 경우 소유자 역할 (roles/owner)을 통해 이 권한이 이미 있을 수 있습니다. 그렇지 않으면 서비스 사용량 관리자 역할 (roles/serviceusage.serviceUsageAdmin)을 통해 이 권한을 얻을 수 있습니다. 역할을 부여하는 방법 알아보기

    gcloud services enable workflows.googleapis.com
  16. 인증을 설정합니다.

    1. 서비스 계정 만들기 IAM 역할(roles/iam.serviceAccountCreator)과 프로젝트 IAM 관리자 역할(roles/resourcemanager.projectIamAdmin)이 있는지 확인합니다. 역할 부여 방법 알아보기
    2. 서비스 계정을 만듭니다.

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      SERVICE_ACCOUNT_NAME을 서비스 계정 이름으로 바꿉니다.

    3. 서비스 계정에 roles/logging.logWriter IAM 역할을 부여합니다.

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

      다음을 바꿉니다.

      • SERVICE_ACCOUNT_NAME: 서비스 계정의 이름입니다.
      • PROJECT_ID: 서비스 계정을 만든 프로젝트 ID입니다.
  17. 서비스 계정 역할 및 권한에 대한 자세한 내용은 Google Cloud 리소스에 액세스할 수 있도록 워크플로 권한 부여를 참고하세요.

  18. 필요한 경우 Git 소스 코드 관리 도구를 다운로드하여 설치합니다.

필요한 역할

빠른 시작을 완료하는 데 필요한 권한을 얻으려면 관리자에게 프로젝트에 대한 다음 IAM 역할을 부여해 달라고 요청하세요.

역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

샘플 워크플로 배포

워크플로를 정의한 후 실행에 사용할 수 있도록 워크플로를 배포합니다. 또한 배포 단계 중 소스 파일을 실행할 수 있는지 확인합니다.

다음 워크플로는 공개 API에 요청을 전송한 후 API의 응답을 반환합니다.

  1. 다음 콘텐츠가 포함된 파일 이름이 myFirstWorkflow.yaml인 텍스트 파일을 만듭니다.

    # This workflow accepts an optional "searchTerm" argument for the Wikipedia API.
    # If no input arguments are provided or "searchTerm" is absent,
    # it will fetch the day of the week in Amsterdam and use it as the search term.
    
    main:
        params: [input]
        steps:
        - validateSearchTermAndRedirectToReadWikipedia:
            switch:
                - condition: '${map.get(input, "searchTerm") != null}'
                  assign:
                    - searchTerm: '${input.searchTerm}'
                  next: readWikipedia
        - getCurrentTime:
            call: http.get
            args:
                url: https://timeapi.io/api/Time/current/zone?timeZone=Europe/Amsterdam
            result: currentTime
        - setFromCallResult:
            assign:
                - searchTerm: '${currentTime.body.dayOfWeek}'
        - 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]}'
  2. 워크플로를 만든 후 배포해도 되지만 워크플로를 실행하지는 마세요.

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

    CLOUD_REGION을 워크플로의 지원되는 위치로 바꿉니다. 코드 샘플에 사용된 기본 리전은 us-central1입니다.

샘플 코드 가져오기

GitHub에서 샘플 코드를 클론할 수 있습니다.

  1. 샘플 앱 저장소를 로컬 머신에 클론합니다.

    C#

    git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Go

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    자바

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

  2. Workflows 샘플 코드가 포함된 디렉터리로 변경합니다.

    C#

    cd dotnet-docs-samples/workflows/api/Workflow.Samples/

    Go

    cd golang-samples/workflows/executions/

    자바

    cd java-docs-samples/workflows/cloud-client/

    Node.js

    cd nodejs-docs-samples/workflows/quickstart/

    Python

    cd python-docs-samples/workflows/cloud-client/

  3. 다음 샘플 코드를 살펴봅니다. 각 샘플 앱은 다음을 실행합니다.

    1. Workflows용 클라우드 클라이언트 라이브러리를 설정합니다.
    2. 워크플로를 실행합니다.
    3. 실행이 종료될 때까지 워크플로 실행을 폴링합니다(지수 백오프 사용).
    4. 실행 결과를 출력합니다.

    C#

    
    using Google.Cloud.Workflows.Common.V1;
    using Google.Cloud.Workflows.Executions.V1;
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    
    public class ExecuteWorkflowSample
    {
        /// <summary>
        /// Execute a workflow and return the execution operation.
        /// </summary>
        /// <param name="projectID">Your Google Cloud Project ID.</param>
        /// <param name="locationID">The region where your workflow is located.</param>
        /// <param name="workflowID">Your Workflow ID.</param>
        /// <returns>
        /// An Execute object representing the completed workflow execution.
        /// </returns>
        public async Task<Execution> ExecuteWorkflow(
            string projectId = "YOUR-PROJECT-ID",
            string locationID = "YOUR-LOCATION-ID",
            string workflowID = "YOUR-WORKFLOW-ID")
        {
            // Initialize the client.
            ExecutionsClient client = await ExecutionsClient.CreateAsync();
    
            // Build the parent location path.
            WorkflowName parent = new WorkflowName(projectId, locationID, workflowID);
    
            // Create an execution request.
            CreateExecutionRequest createExecutionRequest = new CreateExecutionRequest
            {
                ParentAsWorkflowName = parent,
            };
    
            // Execute the operation.
            Execution execution = await client.CreateExecutionAsync(createExecutionRequest);
            Console.WriteLine("- Execution started...");
    
            TimeSpan backoffDelay = TimeSpan.FromSeconds(1);
            TimeSpan maxBackoffDelay = TimeSpan.FromSeconds(16);
    
            // Keep polling the state until the execution finishes, using exponential backoff.
            while (execution.State == Execution.Types.State.Active)
            {
                await Task.Delay(backoffDelay);
    
                // Implement exponential backoff by doubling the delay, but limiting it to a practical duration.
                backoffDelay = (backoffDelay < maxBackoffDelay) ? backoffDelay * 2 : maxBackoffDelay;
    
                execution = await client.GetExecutionAsync(execution.Name);
            }
    
            // Print results.
            Console.WriteLine($"Execution finished with state: {execution.State}");
            Console.WriteLine($"Execution results: {execution.Result}");
    
            // Return the fetched execution.
            return execution;
        }
    }

    Go

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"
    
    	workflowexecutions "google.golang.org/api/workflowexecutions/v1"
    )
    
    // Execute a workflow and print the execution results.
    //
    // For more information about Workflows see:
    // https://cloud.google.com/workflows/docs/overview
    func executeWorkflow(w io.Writer, projectID, workflowID, locationID string) error {
    	// TODO(developer): Uncomment and update the following lines:
    	// projectID := "YOUR_PROJECT_ID"
    	// workflowID := "YOUR_WORKFLOW_ID"
    	// locationID := "YOUR_LOCATION_ID"
    
    	ctx := context.Background()
    
    	// Construct the location path.
    	parent := fmt.Sprintf("projects/%s/locations/%s/workflows/%s", projectID, locationID, workflowID)
    
    	// Create execution client.
    	client, err := workflowexecutions.NewService(ctx)
    	if err != nil {
    		return fmt.Errorf("workflowexecutions.NewService error: %w", err)
    	}
    
    	// Get execution service.
    	service := client.Projects.Locations.Workflows.Executions
    
    	// Build and run the new workflow execution.
    	res, err := service.Create(parent, &workflowexecutions.Execution{}).Do()
    	if err != nil {
    		return fmt.Errorf("service.Create.Do error: %w", err)
    	}
    	fmt.Fprintln(w, "- Execution started...")
    
    	// Set initial value for backoff delay in one second.
    	backoffDelay := time.Second
    
    	for res.State == "ACTIVE" {
    		time.Sleep(backoffDelay)
    
    		// Request the updated state for the execution.
    		getReq := service.Get(res.Name)
    		res, err = getReq.Do()
    		if err != nil {
    			return fmt.Errorf("getReq error: %w", err)
    		}
    
    		// Double the delay to provide exponential backoff (capped at 16 seconds).
    		if backoffDelay < time.Second*16 {
    			backoffDelay *= 2
    		}
    	}
    
    	fmt.Fprintf(w, "Execution finished with state: %s\n", res.State)
    	fmt.Fprintf(w, "Execution results: %s\n", res.Result)
    
    	return nil
    }
    

    Java

    
    import com.google.cloud.workflows.executions.v1.CreateExecutionRequest;
    import com.google.cloud.workflows.executions.v1.Execution;
    import com.google.cloud.workflows.executions.v1.ExecutionsClient;
    import com.google.cloud.workflows.executions.v1.WorkflowName;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    
    public class ExecuteWithoutArguments {
      public static void main(String[] args)
          throws IOException, InterruptedException, ExecutionException {
        String projectId = "your-project-id";
        String location = "your-location"; // For example: us-central1
        String workflowId = "your-workflow-id";
    
        executeWorkflowWithoutArguments(projectId, location, workflowId);
      }
    
      public static void executeWorkflowWithoutArguments(
          String projectId, String location, String workflowId)
          throws IOException, InterruptedException, ExecutionException {
        try (ExecutionsClient executionsClient = ExecutionsClient.create()) {
          WorkflowName parent = WorkflowName.of(projectId, location, workflowId);
    
          CreateExecutionRequest executionRequest =
              CreateExecutionRequest.newBuilder()
                  .setParent(parent.toString())
                  .setExecution(Execution.newBuilder().build())
                  .build();
    
          Execution executionCreated = executionsClient.createExecution(executionRequest);
    
          System.out.println("Created execution: " + executionCreated.getName());
    
          // Wait for execution to finish using exponential backoff
          long backoffDelay = 1_000;
          Execution execution;
          System.out.println("Poll for result...");
          while (true) {
            execution = executionsClient.getExecution(executionCreated.getName());
    
            // Check if execution finished
            if (execution.getState() != Execution.State.ACTIVE) {
              break;
            }
    
            // Wait using exponential backoff
            System.out.println("- Waiting for results...");
            Thread.sleep(backoffDelay);
            backoffDelay *= 2;
          }
    
          System.out.println("Execution finished with state: " + execution.getState().name());
          System.out.println("Execution results: " + execution.getResult());
        }
      }
    }

    Node.js

    const {ExecutionsClient} = require('@google-cloud/workflows');
    const client = new ExecutionsClient();
    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const projectId = 'my-project';
    // const location = 'us-central1';
    // const workflow = 'myFirstWorkflow';
    // const searchTerm = '';
    
    /**
     * Executes a Workflow and waits for the results with exponential backoff.
     * @param {string} projectId The Google Cloud Project containing the workflow
     * @param {string} location The workflow location
     * @param {string} workflow The workflow name
     * @param {string} searchTerm Optional search term to pass to the Workflow as a runtime argument
     */
    async function executeWorkflow(projectId, location, workflow, searchTerm) {
      /**
       * Sleeps the process N number of milliseconds.
       * @param {Number} ms The number of milliseconds to sleep.
       */
      function sleep(ms) {
        return new Promise(resolve => {
          setTimeout(resolve, ms);
        });
      }
      const runtimeArgs = searchTerm ? {searchTerm: searchTerm} : {};
      // Execute workflow
      try {
        const createExecutionRes = await client.createExecution({
          parent: client.workflowPath(projectId, location, workflow),
          execution: {
            // Runtime arguments can be passed as a JSON string
            argument: JSON.stringify(runtimeArgs),