Crea una plantilla de flujo de trabajo (v1)

Crea una nueva plantilla de flujo de trabajo de Dataproc en un proyecto y una ubicación especificados.

Muestra de código

Go

Antes de probar este ejemplo, sigue las instrucciones de configuración para Go que encontrarás en la guía de inicio rápido de Managed Service para Apache Spark sobre las bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Managed Service para Apache Spark para Go.

Para autenticarte en Managed Service para Apache Spark, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Antes de probar este ejemplo, sigue las instrucciones de configuración para Java que encontrarás en la guía de inicio rápido de Managed Service para Apache Spark sobre las bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Managed Service para Apache Spark para Java.

Para autenticarte en Managed Service para Apache Spark, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Antes de probar este ejemplo, sigue las instrucciones de configuración para Node.js que encontrarás en la guía de inicio rápido de Managed Service para Apache Spark sobre las bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Managed Service para Apache Spark para Node.js.

Para autenticarte en Managed Service para Apache Spark, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

'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

Antes de probar este ejemplo, sigue las instrucciones de configuración para Python que encontrarás en la guía de inicio rápido de Managed Service para Apache Spark sobre las bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Managed Service para Apache Spark para Python.

Para autenticarte en Managed Service para Apache Spark, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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}")

¿Qué sigue?

Si quieres buscar y filtrar muestras de código para otros productos de Google Cloud , consulta el navegador de muestras deGoogle Cloud .