Create workflow template (v1)

Create a new Dataproc workflow template in a specified project and location.

Code sample

Go

Before trying this sample, follow the Go setup instructions in the Managed Service for Apache Spark quickstart using client libraries. For more information, see the Managed Service for Apache Spark Go API reference documentation.

To authenticate to Managed Service for Apache Spark, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

Before trying this sample, follow the Java setup instructions in the Managed Service for Apache Spark quickstart using client libraries. For more information, see the Managed Service for Apache Spark Java API reference documentation.

To authenticate to Managed Service for Apache Spark, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

Before trying this sample, follow the Node.js setup instructions in the Managed Service for Apache Spark quickstart using client libraries. For more information, see the Managed Service for Apache Spark Node.js API reference documentation.

To authenticate to Managed Service for Apache Spark, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

'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

Before trying this sample, follow the Python setup instructions in the Managed Service for Apache Spark quickstart using client libraries. For more information, see the Managed Service for Apache Spark Python API reference documentation.

To authenticate to Managed Service for Apache Spark, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.