Membuat template alur kerja (v1)

Membuat template alur kerja Dataproc baru di project dan lokasi yang ditentukan.

Contoh kode

Go

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di panduan memulai Managed Service untuk Apache Spark menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Managed Service untuk Apache Spark.

Untuk melakukan autentikasi ke Managed Service untuk Apache Spark, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import (
	"context"
	"fmt"
	"io"

	dataproc "cloud.google.com/go/dataproc/v2/apiv1"
	"cloud.google.com/go/dataproc/v2/apiv1/dataprocpb"
	"google.golang.org/api/option"
)

// createWorkflowTemplate creates a new Dataproc workflow template in the specified project and location.
func createWorkflowTemplate(ctx context.Context, w io.Writer, projectID string, locationID string, workflowTemplateID string) error {
	var opts []option.ClientOption
	if locationID != "global" {
		opts = append(opts, option.WithEndpoint(fmt.Sprintf("%s-dataproc.googleapis.com:443", locationID)))
	}

	client, err := dataproc.NewWorkflowTemplateClient(ctx, opts...)
	if err != nil {
		return fmt.Errorf("NewWorkflowTemplateClient failed: %w", err)
	}
	defer client.Close()

	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)

	sparkJob := &dataprocpb.SparkJob{
		Driver: &dataprocpb.SparkJob_MainClass{
			MainClass: "org.apache.spark.examples.SparkPi",
		},
		Args: []string{"1000"},
	}

	orderedJob := &dataprocpb.OrderedJob{
		StepId: "example-spark-step",
		JobType: &dataprocpb.OrderedJob_SparkJob{
			SparkJob: sparkJob,
		},
	}

	placement := &dataprocpb.WorkflowTemplatePlacement{
		Placement: &dataprocpb.WorkflowTemplatePlacement_ClusterSelector{
			ClusterSelector: &dataprocpb.ClusterSelector{
				ClusterLabels: map[string]string{
					"example-label": "example-value",
				},
			},
		},
	}

	template := &dataprocpb.WorkflowTemplate{
		Id:        workflowTemplateID,
		Placement: placement,
		Jobs: []*dataprocpb.OrderedJob{
			orderedJob,
		},
	}

	req := &dataprocpb.CreateWorkflowTemplateRequest{
		Parent:   parent,
		Template: template,
	}

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

	fmt.Fprintf(w, "Created workflow template: %s\n", resp.GetName())
	return nil
}

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di panduan memulai Managed Service untuk Apache Spark menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Managed Service untuk Apache Spark.

Untuk melakukan autentikasi ke Managed Service untuk Apache Spark, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import com.google.cloud.dataproc.v1.WorkflowTemplate;
import com.google.cloud.dataproc.v1.WorkflowTemplateServiceClient;
import com.google.cloud.dataproc.v1.WorkflowTemplateServiceSettings;

public class CreateWorkflowTemplate {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project-id";
    String regionId = "example-region-id";
    createWorkflowTemplate(projectId, regionId);
  }

  public static void createWorkflowTemplate(String projectId, String regionId) throws Exception {
    WorkflowTemplateServiceSettings settings =
        WorkflowTemplateServiceSettings.newBuilder()
            .setEndpoint(String.format("%s-dataproc.googleapis.com:443", regionId))
            .build();

    try (WorkflowTemplateServiceClient client = WorkflowTemplateServiceClient.create(settings)) {
      String parent = String.format("projects/%s/regions/%s", projectId, regionId);
      WorkflowTemplate template =
          WorkflowTemplate.newBuilder()
              .setId("example-workflow-template")
              .build();

      WorkflowTemplate response = client.createWorkflowTemplate(parent, template);
      System.out.printf("Created workflow template: %s%n", response.getName());
    }
  }
}

Node.js

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di panduan memulai Managed Service untuk Apache Spark menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Managed Service untuk Apache Spark.

Untuk melakukan autentikasi ke Managed Service untuk Apache Spark, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

'use strict';

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

const client = new WorkflowTemplateServiceClient();

/**
 * Use the createWorkflowTemplate method
 *
 * @param {string} projectId - The Google Cloud project ID.
 * @param {string} locationId - The Google Cloud location (region) ID where the workflow template will be created (for example, 'us-central1').
 * @param {string} workflowTemplateId - The ID of the workflow template to create. This is caller-chosen and must start with a letter, containing only letters, numbers, and hyphens.
 */
async function createWorkflowTemplate(projectId, locationId, workflowTemplateId) {
  try {
    const parent = `projects/${projectId}/locations/${locationId}`;

    const placement = {
      clusterSelector: {
        clusterLabels: {
          'goog-dataproc-cluster-name': 'example-cluster',
        },
      },
    };

    const jobs = [
      {
        stepId: 'example-step',
        sparkJob: {
          mainJarFileUri: 'file:///usr/lib/spark/examples/jars/spark-examples.jar',
          args: ['1000'],
        },
      },
    ];

    const template = {
      id: workflowTemplateId,
      placement,
      jobs,
    };

    const [createdTemplate] = await client.createWorkflowTemplate({
      parent,
      template,
    });

    console.log(`Created workflow template: ${createdTemplate.name}`);
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Workflow template already exists: ${err.message}`);
    } else if (err.code) {
      console.error(`Google API error [code ${err.code}]: ${err.message}`);
    } else {
      throw err;
    }
  }
}

module.exports = { createWorkflowTemplate };

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di panduan memulai Managed Service untuk Apache Spark menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Managed Service untuk Apache Spark.

Untuk melakukan autentikasi ke Managed Service untuk Apache Spark, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import uuid

import google.api_core.exceptions
from google.cloud import dataproc_v1


def create_workflow_template(project_id: str, region_id: str) -> None:
    """Creates a Dataproc workflow template in a specified region.

    Args:
        project_id: The Google Cloud project ID (for example, 'example-project-id').
        region_id: The Google Cloud region where the service is located (for example, 'us-central1').
    """
    client = dataproc_v1.WorkflowTemplateServiceClient(
        client_options={"api_endpoint": f"{region_id}-dataproc.googleapis.com:443"}
    )

    parent = f"projects/{project_id}/regions/{region_id}"
    template = dataproc_v1.WorkflowTemplate(
        id=f"example-workflow-template-{uuid.uuid4().hex[:8]}",
    )

    try:
        response = client.create_workflow_template(
            parent=parent,
            template=template,
        )
        print(f"Created workflow template: {response.name}")
    except google.api_core.exceptions.AlreadyExists:
        print(f"Workflow template already exists: {template.id}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to create workflow template: {error}")

Langkah berikutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contohGoogle Cloud .