建立工作階段範本 (v1)

在指定區域建立新的 Dataproc 工作階段範本。

程式碼範例

Go

在試用這個範例之前,請先按照「使用用戶端程式庫的 Managed Service for Apache Spark 快速入門導覽課程」中的 Go 設定操作說明進行操作。詳情請參閱 Managed Service for Apache Spark Go API 參考文件。

如要向 Managed Service for Apache Spark 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


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

// createSessionTemplate creates a Dataproc session template in the specified region.
func createSessionTemplate(ctx context.Context, w io.Writer, projectID string, locationID string, sessionTemplateID string) error {
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)
	sessionTemplate := &dataprocpb.SessionTemplate{
		Name:        fmt.Sprintf("projects/%s/locations/%s/sessionTemplates/%s", projectID, locationID, sessionTemplateID),
		Description: "Sample Dataproc Session Template",
		SessionConfig: &dataprocpb.SessionTemplate_JupyterSession{
			JupyterSession: &dataprocpb.JupyterConfig{
				Kernel:      dataprocpb.JupyterConfig_PYTHON,
				DisplayName: "Example Jupyter Session",
			},
		},
	}

	// Dataproc API calls require regional endpoints.
	endpoint := fmt.Sprintf("%s-dataproc.googleapis.com:443", locationID)
	client, err := dataproc.NewSessionTemplateControllerClient(ctx, option.WithEndpoint(endpoint))
	if err != nil {
		return fmt.Errorf("NewSessionTemplateControllerClient failed: %w", err)
	}
	defer client.Close()

	req := &dataprocpb.CreateSessionTemplateRequest{
		Parent:          parent,
		SessionTemplate: sessionTemplate,
	}

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

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

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 Managed Service for Apache Spark 快速入門導覽課程」中的 Java 設定操作說明進行操作。詳情請參閱 Managed Service for Apache Spark Java API 參考文件。

如要向 Managed Service for Apache Spark 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

import com.google.cloud.dataproc.v1.JupyterConfig;
import com.google.cloud.dataproc.v1.SessionTemplate;
import com.google.cloud.dataproc.v1.SessionTemplateControllerClient;
import com.google.cloud.dataproc.v1.SessionTemplateControllerSettings;
import java.io.IOException;

public class CreateSessionTemplate {

  public static void main(String[] args) throws IOException {
    String projectId = "example-project-id";
    String locationId = "example-location-id";
    String sessionTemplateId = "example-session-template-id";
    createSessionTemplate(projectId, locationId, sessionTemplateId);
  }

  public static void createSessionTemplate(
      String projectId, String locationId, String sessionTemplateId) throws IOException {
    // Configure regional endpoint for Dataproc control plane operations
    String endpoint = String.format("%s-dataproc.googleapis.com:443", locationId);
    SessionTemplateControllerSettings settings =
        SessionTemplateControllerSettings.newBuilder().setEndpoint(endpoint).build();

    try (SessionTemplateControllerClient client = SessionTemplateControllerClient.create(settings)) {
      String parent = String.format("projects/%s/locations/%s", projectId, locationId);
      SessionTemplate sessionTemplate =
          SessionTemplate.newBuilder()
              .setName(String.format("%s/sessionTemplates/%s", parent, sessionTemplateId))
              .setDescription("Session template configured with Python Jupyter kernel")
              .setJupyterSession(
                  JupyterConfig.newBuilder()
                      .setKernel(JupyterConfig.Kernel.PYTHON)
                      .setDisplayName("Example Jupyter Session")
                      .build())
              .build();

      SessionTemplate response = client.createSessionTemplate(parent, sessionTemplate);
      System.out.println("Created session template: " + response.getName());
    }
  }
}

Node.js

在試用這個範例之前,請先按照「使用用戶端程式庫的 Managed Service for Apache Spark 快速入門導覽課程」中的 Node.js 設定操作說明進行操作。詳情請參閱 Managed Service for Apache Spark Node.js API 參考文件。

如要向 Managed Service for Apache Spark 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

'use strict';

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

/**
 * Creates a Dataproc session template.
 *
 * @param {string} projectId - The Google Cloud project ID where the session template is created.
 * @param {string} locationId - The Dataproc region where the session template resides (for example, 'us-central1').
 * @param {string} sessionTemplateId - The caller-specified identifier for the session template, conforming to RFC 1035 (1-63 characters, matching [a-z]([-a-z0-9]*[a-z0-9])?).
 */
async function createSessionTemplate(projectId, locationId, sessionTemplateId) {
  // Dataproc regional endpoints require configuring apiEndpoint with the matching region.
  const client = new SessionTemplateControllerClient({
    apiEndpoint: `${locationId}-dataproc.googleapis.com`,
  });

  try {
    const parent = `projects/${projectId}/locations/${locationId}`;
    const sessionTemplate = {
      name: `${parent}/sessionTemplates/${sessionTemplateId}`,
      jupyterSession: {
        kernel: 'PYTHON',
        displayName: 'example-jupyter-session',
      },
    };

    const [response] = await client.createSessionTemplate({
      parent,
      sessionTemplate,
    });

    console.log(`Created session template: ${response.name}`);
    return response;
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Session template already exists: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else {
      throw err;
    }
  }
}

module.exports = { createSessionTemplate };

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Managed Service for Apache Spark 快速入門導覽課程」中的 Python 設定操作說明進行操作。詳情請參閱 Managed Service for Apache Spark Python API 參考文件。

如要向 Managed Service for Apache Spark 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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


def create_session_template(
    project_id: str, location_id: str, session_template_id: str
) -> None:
    """Creates a Dataproc session template.

    Args:
        project_id: The Google Cloud project ID.
        location_id: The Dataproc region for the session template, for example us-central1.
        session_template_id: The caller-chosen identifier for the session template.
    """
    endpoint = f"{location_id}-dataproc.googleapis.com:443"
    client = dataproc_v1.SessionTemplateControllerClient(
        client_options=ClientOptions(api_endpoint=endpoint)
    )

    parent = f"projects/{project_id}/locations/{location_id}"
    session_template = dataproc_v1.SessionTemplate(
        name=f"projects/{project_id}/locations/{location_id}/sessionTemplates/{session_template_id}",
        jupyter_session=dataproc_v1.JupyterConfig(
            kernel=dataproc_v1.JupyterConfig.Kernel.PYTHON,
            display_name="example-jupyter-session",
        ),
    )

    try:
        response = client.create_session_template(
            parent=parent,
            session_template=session_template,
        )
        print(f"Created session template: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to create session template: {error}")

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽工具。