Job aus Vorlage erstellen (v1beta3)

Erstellen Sie einen neuen Dataflow-Job mit einer klassischen Vorlage, die in Cloud Storage gespeichert ist.

Codebeispiel

Go

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Dataflow zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import (
	"context"
	"fmt"
	"io"

	dataflow "cloud.google.com/go/dataflow/apiv1beta3"
	dataflowpb "cloud.google.com/go/dataflow/apiv1beta3/dataflowpb"
)

// createJobFromTemplate launches a Dataflow job using a classic Cloud Storage template.
func createJobFromTemplate(ctx context.Context, w io.Writer, projectID string, locationID string, jobName string, gcsPath string) error {
	client, err := dataflow.NewTemplatesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTemplatesClient: %w", err)
	}
	defer client.Close()

	req := &dataflowpb.CreateJobFromTemplateRequest{
		ProjectId: projectID,
		Location:  locationID,
		JobName:   jobName,
		Template: &dataflowpb.CreateJobFromTemplateRequest_GcsPath{
			GcsPath: gcsPath,
		},
		Parameters: map[string]string{
			"inputFile": "gs://apache-beam-samples/shakespeare/kinglear.txt",
			"output":    "gs://example-bucket/output",
		},
	}

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

	fmt.Fprintf(w, "Created job: %s\nJob ID: %s\nState: %s\n", job.GetName(), job.GetId(), job.GetCurrentState())
	return nil
}

Node.js

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Dataflow zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

'use strict';

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

const client = new TemplatesServiceClient();

/**
 * Use the createJobFromTemplate method
 *
 * @param {string} projectId - The ID of the Google Cloud project that the job belongs to.
 * @param {string} locationId - The regional endpoint (for example, 'us-central1') to which to direct the request.
 * @param {string} jobName - The caller-chosen name to use for the created job. Must match '[a-z]([-a-z0-9]{0,1022}[a-z0-9])?'.
 * @param {string} gcsPath - A Cloud Storage path to the template from which to create the job. Must be a valid Cloud Storage URL beginning with 'gs://'.
 */
async function createJobFromTemplate(projectId, locationId, jobName, gcsPath) {
  try {
    const request = {
      projectId,
      location: locationId,
      jobName,
      gcsPath,
    };

    const [response] = await client.createJobFromTemplate(request);
    console.log(`Job created with ID: ${response.id}`);
    console.log(`Job status: ${response.currentState}`);
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Job already exists: ${err.message}`);
    } else if (err.code === status.NOT_FOUND) {
      console.error(`Resource not found: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid request argument: ${err.message}`);
    } else {
      console.error(`API error: ${err.message}`);
    }
  }
}

module.exports = { createJobFromTemplate };

Python

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Dataflow zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import google.api_core.exceptions
from google.cloud import dataflow_v1beta3


def create_job_from_template(
    project_id: str, location_id: str, job_name: str, gcs_path: str
) -> None:
    """Creates a Dataflow job from a Cloud Storage template.

    Args:
        project_id: The ID of the Google Cloud project that owns the Dataflow
          job.
        location_id: The regional endpoint that contains the job (for example,
          'us-central1').
        job_name: The unique name for the created job.
        gcs_path: The Cloud Storage path to the template file, starting with
          'gs://'.
    """
    client = dataflow_v1beta3.TemplatesServiceClient()

    # Supply required template parameters for execution
    parameters = {
        "inputFile": "gs://dataflow-samples/shakespeare/kinglear.txt",
        "output": f"gs://{project_id}/output",
    }

    request = dataflow_v1beta3.CreateJobFromTemplateRequest(
        project_id=project_id,
        location=location_id,
        job_name=job_name,
        gcs_path=gcs_path,
        parameters=parameters,
    )

    try:
        response = client.create_job_from_template(request=request)
        print(f"Created Dataflow job: {response.name}")
        print(f"Job ID: {response.id}")
        print(f"Current state: {response.current_state.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to create job from template: {error}")

Nächste Schritte

Wenn Sie nach Codebeispielen für andere Produkte von Google Cloud suchen und filtern möchten, können Sie den Beispielbrowser fürGoogle Cloud verwenden.