템플릿 실행(v1beta3)

Cloud Storage에 저장된 Dataflow 템플릿을 실행합니다.

코드 샘플

Go

Dataflow에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import (
	"context"
	"fmt"
	"io"

	dataflow "cloud.google.com/go/dataflow/apiv1beta3"
	dataflowpb "cloud.google.com/go/dataflow/apiv1beta3/dataflowpb"
)

// launchTemplate executes a Dataflow template stored in Cloud Storage.
func launchTemplate(ctx context.Context, w io.Writer, projectID string, locationID string, gcsPath string) error {
	client, err := dataflow.NewTemplatesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTemplatesClient failed: %w", err)
	}
	defer client.Close()

	launchParameters := &dataflowpb.LaunchTemplateParameters{
		JobName: "example-template-job",
		Parameters: map[string]string{
			"inputFile": "gs://dataflow-samples/shakespeare/kinglear.txt",
			"output":    "gs://example-bucket/output",
		},
	}

	req := &dataflowpb.LaunchTemplateRequest{
		ProjectId: projectID,
		Location:  locationID,
		Template: &dataflowpb.LaunchTemplateRequest_GcsPath{
			GcsPath: gcsPath,
		},
		LaunchParameters: launchParameters,
	}

	resp, err := client.LaunchTemplate(ctx, req)
	if err != nil {
		return fmt.Errorf("LaunchTemplate failed: %w", err)
	}

	fmt.Fprintf(w, "Launched Dataflow job ID: %s\n", resp.GetJob().GetId())
	return nil
}

Java

Dataflow에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.dataflow.v1beta3.LaunchTemplateParameters;
import com.google.dataflow.v1beta3.LaunchTemplateRequest;
import com.google.dataflow.v1beta3.LaunchTemplateResponse;
import com.google.dataflow.v1beta3.TemplatesServiceClient;
import java.io.IOException;

public class LaunchTemplate {

  public static void main(String[] args) throws IOException {
    String projectId = "example-project-id";
    String locationId = "us-central1";
    String gcsPath = "gs://example-bucket/templates/example-template";
    launchTemplate(projectId, locationId, gcsPath);
  }

  public static void launchTemplate(String projectId, String locationId, String gcsPath)
      throws IOException {
    try (TemplatesServiceClient client = TemplatesServiceClient.create()) {
      // Configure launch parameters including the unique Dataflow job name
      LaunchTemplateParameters launchParameters =
          LaunchTemplateParameters.newBuilder()
              .setJobName("example-template-job")
              .build();

      LaunchTemplateRequest request =
          LaunchTemplateRequest.newBuilder()
              .setProjectId(projectId)
              .setLocation(locationId)
              .setGcsPath(gcsPath)
              .setLaunchParameters(launchParameters)
              .build();

      LaunchTemplateResponse response = client.launchTemplate(request);
      System.out.println("Launched job ID: " + response.getJob().getId());
      System.out.println("Job state: " + response.getJob().getCurrentState());
    }
  }
}

Node.js

Dataflow에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

'use strict';

const {TemplatesServiceClient} = require('@google-cloud/dataflow');
const {status} = require('@grpc/grpc-js');

const client = new TemplatesServiceClient();

/**
 * Use the launchTemplate method
 *
 * @param {string} projectId - The ID of the Google Cloud Platform project that the job belongs to.
 * @param {string} locationId - The regional endpoint to which to direct the request (e.g., 'us-central1').
 * @param {string} gcsPath - A Cloud Storage path to the template to use to create the job, beginning with 'gs://'.
 */
async function launchTemplate(projectId, locationId, gcsPath) {
  try {
    const launchParameters = {
      jobName: 'example-template-job',
    };

    const request = {
      projectId,
      location: locationId,
      gcsPath,
      launchParameters,
    };

    const [response] = await client.launchTemplate(request);
    console.log(`Launched template job ID: ${response.job?.id}`);
    console.log(`Job state: ${response.job?.currentState}`);
  } catch (err) {
    if (err.code === status.INVALID_ARGUMENT) {
      console.error('Invalid argument provided:', err.message);
    } else if (err.code === status.NOT_FOUND) {
      console.error('Template or resource not found:', err.message);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error('Permission denied for launch request:', err.message);
    } else {
      console.error(`API error (code ${err.code}):`, err.message);
    }
  }
}

module.exports = { launchTemplate };

Python

Dataflow에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import google.api_core.exceptions
from google.cloud import dataflow_v1beta3


def launch_template(
    project_id: str, location_id: str, gcs_path: str, job_name: str
) -> None:
    """Launches a Dataflow job using a template stored in Cloud Storage.

    Args:
        project_id: The ID of the Google Cloud project that the job belongs to.
        location_id: The regional endpoint to which to direct the request (for
          example, 'us-central1').
        gcs_path: A Cloud Storage path to the template to use to create the job.
          Must be a valid Cloud Storage URL, beginning with 'gs://'.
        job_name: The caller-specified Dataflow job name. Must match the
          regular expression `[a-z]([-a-z0-9]{0,1022}[a-z0-9])?`.
    """
    client = dataflow_v1beta3.TemplatesServiceClient()

    launch_parameters = dataflow_v1beta3.LaunchTemplateParameters(
        job_name=job_name,
        parameters={
            "inputFile": "gs://dataflow-samples/shakespeare/kinglear.txt",
            "output": f"gs://{project_id}/output",
        },
    )

    request = dataflow_v1beta3.LaunchTemplateRequest(
        project_id=project_id,
        location=location_id,
        gcs_path=gcs_path,
        launch_parameters=launch_parameters,
    )

    try:
        response = client.launch_template(request=request)
        print(f"Launched job ID: {response.job.id}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to launch template: {error}")

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저 참조하기