Créer un modèle de workflow (v1)

Créez un modèle de workflow Dataproc dans un projet et un emplacement spécifiés.

Exemple de code

Go

Avant d'essayer cet exemple, suivez les instructions de configuration pour Go décrites dans le guide de démarrage rapide de Managed Service pour Apache Spark à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Managed Service pour Apache Spark en langage Go.

Pour vous authentifier auprès de Managed Service pour Apache Spark, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement 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

Avant d'essayer cet exemple, suivez les instructions de configuration pour Java décrites dans le guide de démarrage rapide de Managed Service pour Apache Spark à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Managed Service pour Apache Spark en langage Java.

Pour vous authentifier auprès de Managed Service pour Apache Spark, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement 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

Avant d'essayer cet exemple, suivez les instructions de configuration pour Node.js décrites dans le guide de démarrage rapide de Managed Service pour Apache Spark à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Managed Service pour Apache Spark en langage Node.js.

Pour vous authentifier auprès de Managed Service pour Apache Spark, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement 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

Avant d'essayer cet exemple, suivez les instructions de configuration pour Python décrites dans le guide de démarrage rapide de Managed Service pour Apache Spark à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Managed Service pour Apache Spark en langage Python.

Pour vous authentifier auprès de Managed Service pour Apache Spark, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement 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}")

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud , consultez l'explorateur d'exemplesGoogle Cloud .