创建和运行基本作业

本文档介绍批量作业创建的基础知识:如何基于脚本或容器映像创建和运行作业,以及如何使用预定义和自定义变量。如需详细了解如何创建和运行作业,请参阅作业创建和执行概览

准备工作

  • 如果您之前未使用过 Batch,请查看 Batch 使用入门,并通过完成项目和用户的前提条件来启用 Batch。
  • 如需获取创建作业所需的权限,请让管理员授予您以下 IAM 角色:

    如需详细了解如何授予角色,请参阅管理访问权限

    您也可以通过自定义角色或其他预定义角色来获取所需的权限。

  • 每次创建作业时,请确保作业具有有效的网络配置。
    • 如果您没有任何特定网络要求,也未修改项目的默认网络,则无需执行任何操作。
    • 否则,如果您的项目或工作负载要求您使用自定义网络,则在创建作业时需要配置网络。在创建基本作业之前,了解如何为作业配置网络,以便修改以下示例以满足您的网络要求。
    如需详细了解作业的默认网络配置以及为作业配置网络的时间和方式,请参阅批量网络概览

创建基本作业

如需了解可以为作业指定的所有字段,请参阅 projects.locations.jobs REST 资源的参考文档。总而言之,作业包含一个或多个任务的数组,所有任务都运行一个或多个可运行项,后者是作业的可执行脚本和/或容器。为涵盖基础知识,本部分介绍如何仅使用一个可运行(脚本或容器映像)创建示例作业:

  • 如果要使用 Batch 写入运行容器映像的作业,请参阅创建容器作业
  • 或者,如果您不确定是否要使用容器映像,或者不熟悉容器,建议您创建脚本作业

这两种类型的作业的示例任务包含一个任务组,该任务组包含 4 个任务。每个任务都会输出一条消息及其索引到标准输出和 Cloud Logging。此作业的定义指定 2 个并行处理,这表示该作业应在 2 个虚拟机上运行,以允许同时运行 2 个任务。

创建基本容器作业

您可以选择或创建容器映像,以提供您的作业在任何计算环境中运行的代码和依赖项。如需了解详情,请参阅使用容器映像在虚拟机实例上运行容器

您可以使用 Google Cloud 控制台、gcloud CLI、Batch API、Go、Java、Node.js 或 Python 创建基本容器作业。

控制台

如需使用 Google Cloud 控制台创建基本容器作业,请执行以下操作:

  1. 在 Google Cloud 控制台中,转到作业列表页面。

    转到作业列表

  2. 点击 创建创建批量作业页面会打开。

  3. 作业名称字段中,输入作业名称。

    例如,输入 example-basic-job

  4. 区域字段中,为此作业选择位置

    例如,选择 us-central1 (Iowa)(默认)。

  5. 可用区字段中,执行以下操作之一:

    • 如果您希望将此作业限制为仅在特定可用区运行,请选择一个可用区。

    • 否则,请选择 any

    例如,选择 any(默认)。

  6. 虚拟机预配模型部分,为此作业的虚拟机选择预配模型之一:

    • 如果您的作业能够承受抢占,并且您希望使用打折的虚拟机,请选择 Spot

    • 否则,请选择标准

    例如,选择标准(默认)。

  7. 选择以下机器系列之一:

    • 对于常见工作负载,请点击通用

    • 对于性能密集型的工作负载,点击计算优化

    • 对于内存密集型工作负载,请点击内存优化

    例如,点击通用(默认)。

  8. 系列字段中,为此作业的虚拟机选择一个机器系列

    例如,如果您为机器系列选择了通用,请选择 E2(默认)。

  9. 机器类型字段中,为此作业的虚拟机选择机器类型。

    例如,如果您为机器系列选择了 E2,请选择 e2-medium(2 个 vCPU,4 GB 内存)(默认)。

  10. New runnable 窗格中,执行以下操作:

    1. 选择容器映像网址(默认)。

    2. 容器映像网址字段中,输入要为此作业中的每个任务运行的容器映像的网址。

      例如,如需使用 busybox Docker 容器映像,请输入以下网址:

      gcr.io/google-containers/busybox
      
    3. 可选:如需替换容器映像的 ENTRYPOINT 命令,请在入口点字段中输入一个命令。

      例如,输入以下内容:

      /bin/sh
      
    4. 可选:如需替换容器映像的 CMD 命令,请执行以下操作:

      1. 选中替换容器映像的 CMD 命令复选框。系统会显示一个文本框。

      2. 在文本框中输入一个或多个命令,每行一个。

        例如,输入以下命令:

        -c
        echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.
        
    5. 点击完成

  11. 任务数字段中,输入此作业的任务数。该值必须是介于 110000 之间的整数。

    例如,输入 4

  12. 并行处理字段中,输入要并发运行的任务数量。此数字不能大于任务总数,并且必须是 11000 之间的整数。

    例如,输入 2

  13. 任务资源部分,通过执行以下操作来指定每项任务所需的虚拟机资源量:

    1. 核心数字段中,输入 vCPU 的数量。

      例如,输入 1(默认值)。

    2. 内存字段中,输入 RAM 量(以 GB 为单位)。

      例如,输入 0.5(默认值)。

  14. 点击创建

作业列表页面会显示您创建的作业。

gcloud

如需使用 gcloud CLI 创建基本容器作业,请执行以下操作:

  1. 创建一个用于指定作业的配置详情的 JSON 文件。例如,如需创建基本容器作业,请创建包含以下内容的 JSON 文件。如需详细了解可以为作业指定的所有字段,请参阅 projects.locations.jobs REST 资源的参考文档。

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "container": {
                                CONTAINER
                            }
                        }
                    ],
                    "computeResource": {
                        "cpuMilli": CORES,
                        "memoryMib": MEMORY
                    },
                    "maxRetryCount": MAX_RETRY_COUNT,
                    "maxRunDuration": "MAX_RUN_DURATION"
                },
                "taskCount": TASK_COUNT,
                "parallelism": PARALLELISM
            }
        ]
    }
    

    请替换以下内容:

    • CONTAINER:每个任务运行的容器
    • CORES:可选。要分配给每个任务的核心数量(具体来讲,就是 vCPU),通常代表半个物理核心,单位为毫安单位。如果未指定 cpuMilli 字段,则将该值设置为 2000(2 个 vCPU)。
    • MEMORY:可选。为每个任务分配的内存容量(以 MB 为单位)。如果未指定 memoryMib 字段,则将该值设置为 2000 (2 GB)。
    • MAX_RETRY_COUNT:可选。任务的重试次数上限。该值必须是介于 010 之间的整数。如果未指定 maxRetryCount 字段,则将该值设置为 0,这意味着不会重试任务。
    • MAX_RUN_DURATION:可选。允许任务在重试或失败之前运行的最长时间,格式为以秒为单位的值,后跟 s。如果未指定 maxRunDuration 字段,则该值将设置为 604800s(7 天),这是最大值。
    • TASK_COUNT:可选。作业的任务数。该值必须是介于 110000 之间的整数。如果未指定 taskCount 字段,则将该值设置为 1
    • PARALLELISM:可选。作业并发运行的任务数。该数字不能大于任务数,并且必须是 11000 之间的整数。如果未指定 parallelism 字段,则将该值设置为 1
  2. 使用 gcloud batch jobs submit 命令创建作业。

    gcloud batch jobs submit JOB_NAME \
      --location LOCATION \
      --config JSON_CONFIGURATION_FILE
    

    请替换以下内容:

    • JOB_NAME:作业的名称。
    • LOCATION:作业的位置
    • JSON_CONFIGURATION_FILE:包含作业配置详细信息的 JSON 文件的路径。

例如,如需创建使用 busybox Docker 容器映像运行任务的作业,请执行以下操作:

  1. 在当前目录中创建一个名为 hello-world-container.json 且包含以下内容的 JSON 文件:

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "container": {
                                "imageUri": "gcr.io/google-containers/busybox",
                                "entrypoint": "/bin/sh",
                                "commands": [
                                    "-c",
                                    "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                                ]
                            }
                        }
                    ],
                    "computeResource": {
                        "cpuMilli": 2000,
                        "memoryMib": 16
                    },
                    "maxRetryCount": 2,
                    "maxRunDuration": "3600s"
                },
                "taskCount": 4,
                "parallelism": 2
            }
        ],
        "allocationPolicy": {
            "instances": [
                {
                    "policy": { "machineType": "e2-standard-4" }
                }
            ]
        },
        "labels": {
            "department": "finance",
            "env": "testing"
        },
        "logsPolicy": {
            "destination": "CLOUD_LOGGING"
        }
    }
    
  2. 运行以下命令:

    gcloud batch jobs submit example-container-job \
      --location us-central1 \
      --config hello-world-container.json
    

API

如需使用 Batch API 创建基本容器作业,请使用 jobs.create 方法。如需详细了解可以为作业指定的所有字段,请参阅 projects.locations.jobs REST 资源的参考文档。

POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs?job_id=JOB_NAME

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "container": {
                            CONTAINER
                        }
                    }
                ],
                "computeResource": {
                    "cpuMilli": CORES,
                    "memoryMib": MEMORY
                },
                "maxRetryCount": MAX_RETRY_COUNT,
                "maxRunDuration": "MAX_RUN_DURATION"
            },
            "taskCount": TASK_COUNT,
            "parallelism": PARALLELISM
        }
    ]
}

请替换以下内容:

  • PROJECT_ID:项目的项目 ID
  • LOCATION:作业的位置
  • JOB_NAME:作业的名称。
  • CONTAINER:每个任务运行的容器
  • CORES:可选。要分配给每个任务的核心数量(具体来讲,就是 vCPU),通常代表半个物理核心,单位为毫单位。如果未指定 cpuMilli 字段,则将该值设置为 2000(2 个 vCPU)。
  • MEMORY:可选。为每个任务分配的内存容量(以 MB 为单位)。如果未指定 memoryMib 字段,则将该值设置为 2000 (2 GB)。
  • MAX_RETRY_COUNT:可选。任务的重试次数上限。该值必须是介于 010 之间的整数。如果未指定 maxRetryCount 字段,则将该值设置为 0,这意味着不会重试任务。
  • MAX_RUN_DURATION:可选。重试或失败之前允许任务运行的最长时间,格式为秒,后跟 s。如果未指定 maxRunDuration 字段,则该值将设置为 604800s(7 天),这是最大值。
  • TASK_COUNT:可选。作业的任务数,必须是介于 110000 之间的整数。如果未指定 taskCount 字段,则将该值设置为 1
  • PARALLELISM:可选。作业并发运行的任务数。该数字不能大于任务数,并且必须是 11000 之间的整数。如果未指定 parallelism 字段,则将该值设置为 1

例如,如需创建使用 busybox Docker 容器映像运行任务的作业,请使用以下请求:

POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/jobs?job_id=example-container-job

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "container": {
                            "imageUri": "gcr.io/google-containers/busybox",
                            "entrypoint": "/bin/sh",
                            "commands": [
                                "-c",
                                "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                            ]
                        }
                    }
                ],
                "computeResource": {
                    "cpuMilli": 2000,
                    "memoryMib": 16
                },
                "maxRetryCount": 2,
                "maxRunDuration": "3600s"
            },
            "taskCount": 4,
            "parallelism": 2
        }
    ],
    "allocationPolicy": {
        "instances": [
            {
                "policy": { "machineType": "e2-standard-4" }
            }
        ]
    },
    "labels": {
        "department": "finance",
        "env": "testing"
    },
    "logsPolicy": {
        "destination": "CLOUD_LOGGING"
    }
}

其中 PROJECT_ID 是项目的项目 ID

Go

Go

如需了解详情,请参阅 Batch Go API 参考文档

如需向 Batch 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
	durationpb "google.golang.org/protobuf/types/known/durationpb"
)

// Creates and runs a job that runs the specified container
func createContainerJob(w io.Writer, projectID, region, jobName string) error {
	// projectID := "your_project_id"
	// region := "us-central1"
	// jobName := "some-job"

	ctx := context.Background()
	batchClient, err := batch.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer batchClient.Close()

	container := &batchpb.Runnable_Container{
		ImageUri:   "gcr.io/google-containers/busybox",
		Commands:   []string{"-c", "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."},
		Entrypoint: "/bin/sh",
	}

	// We can specify what resources are requested by each task.
	resources := &batchpb.ComputeResource{
		// CpuMilli is milliseconds per cpu-second. This means the task requires 2 whole CPUs.
		CpuMilli:  2000,
		MemoryMib: 16,
	}

	taskSpec := &batchpb.TaskSpec{
		Runnables: []*batchpb.Runnable{{
			Executable: &batchpb.Runnable_Container_{Container: container},
		}},
		ComputeResource: resources,
		MaxRunDuration: &durationpb.Duration{
			Seconds: 3600,
		},
		MaxRetryCount: 2,
	}

	// Tasks are grouped inside a job using TaskGroups.
	taskGroups := []*batchpb.TaskGroup{
		{
			TaskCount: 4,
			TaskSpec:  taskSpec,
		},
	}

	// Policies are used to define on what kind of virtual machines the tasks will run on.
	// In this case, we tell the system to use "e2-standard-4" machine type.
	// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
	allocationPolicy := &batchpb.AllocationPolicy{
		Instances: []*batchpb.AllocationPolicy_InstancePolicyOrTemplate{{
			PolicyTemplate: &batchpb.AllocationPolicy_InstancePolicyOrTemplate_Policy{
				Policy: &batchpb.AllocationPolicy_InstancePolicy{
					MachineType: "e2-standard-4",
				},
			},
		}},
	}

	// We use Cloud Logging as it's an out of the box available option
	logsPolicy := &batchpb.LogsPolicy{
		Destination: batchpb.LogsPolicy_CLOUD_LOGGING,
	}

	jobLabels := map[string]string{"env": "testing", "type": "container"}

	// The job's parent is the region in which the job will run
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, region)

	job := batchpb.Job{
		TaskGroups:       taskGroups,
		AllocationPolicy: allocationPolicy,
		Labels:           jobLabels,
		LogsPolicy:       logsPolicy,
	}

	req := &batchpb.CreateJobRequest{
		Parent: parent,
		JobId:  jobName,
		Job:    &job,
	}

	created_job, err := batchClient.CreateJob(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create job: %w", err)
	}

	fmt.Fprintf(w, "Job created: %v\n", created_job)

	return nil
}

Java

Java

如需了解详情,请参阅 Batch Java API 参考文档

如需向 Batch 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.batch.v1.AllocationPolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicyOrTemplate;
import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.ComputeResource;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.LogsPolicy.Destination;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.Runnable.Container;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateWithContainerNoMounting {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the region you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "europe-central2";

    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "JOB_NAME";

    createContainerJob(projectId, region, jobName);
  }

  // This method shows how to create a sample Batch Job that will run a simple command inside a
  // container on Cloud Compute instances.
  public static void createContainerJob(String projectId, String region, String jobName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `batchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      // Define what will be done as part of the job.
      Runnable runnable =
          Runnable.newBuilder()
              .setContainer(
                  Container.newBuilder()
                      .setImageUri("gcr.io/google-containers/busybox")
                      .setEntrypoint("/bin/sh")
                      .addCommands("-c")
                      .addCommands(
                          "echo Hello world! This is task ${BATCH_TASK_INDEX}. "
                              + "This job has a total of ${BATCH_TASK_COUNT} tasks.")
                      .build())
              .build();

      // We can specify what resources are requested by each task.
      ComputeResource computeResource =
          ComputeResource.newBuilder()
              // In milliseconds per cpu-second. This means the task requires 2 whole CPUs.
              .setCpuMilli(2000)
              // In MiB.
              .setMemoryMib(16)
              .build();

      TaskSpec task =
          TaskSpec.newBuilder()
              // Jobs can be divided into tasks. In this case, we have only one task.
              .addRunnables(runnable)
              .setComputeResource(computeResource)
              .setMaxRetryCount(2)
              .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
              .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder().setTaskCount(4).setTaskSpec(task).build();

      // Policies are used to define on what kind of virtual machines the tasks will run on.
      // In this case, we tell the system to use "e2-standard-4" machine type.
      // Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
      InstancePolicy instancePolicy =
          InstancePolicy.newBuilder().setMachineType("e2-standard-4").build();

      AllocationPolicy allocationPolicy =
          AllocationPolicy.newBuilder()
              .addInstances(InstancePolicyOrTemplate.newBuilder().setPolicy(instancePolicy).build())
              .build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              .setAllocationPolicy(allocationPolicy)
              .putLabels("env", "testing")
              .putLabels("type", "container")
              // We use Cloud Logging as it's an out of the box available option.
              .setLogsPolicy(
                  LogsPolicy.newBuilder().setDestination(Destination.CLOUD_LOGGING).build())
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.getName());
    }
  }
}

Node.js

Node.js

如需了解详情,请参阅 Batch Node.js API 参考文档

如需向 Batch 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
/**
 * The region you want to the job to run in. The regions that support Batch are listed here:
 * https://cloud.google.com/batch/docs/get-started#locations
 */
// const region = 'us-central-1';
/**
 * The name of the job that will be created.
 * It needs to be unique for each project and region pair.
 */
// const jobName = 'YOUR_JOB_NAME';

// Imports the Batch library
const batchLib = require('@google-cloud/batch');
const batch = batchLib.protos.google.cloud.batch.v1;

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

// Define what will be done as part of the job.
const task = new batch.TaskSpec();
const runnable = new batch.Runnable();
runnable.container = new batch.Runnable.Container();
runnable.container.imageUri = 'gcr.io/google-containers/busybox';
runnable.container.entrypoint = '/bin/sh';
runnable.container.commands = [
  '-c',
  'echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.',
];
task.runnables = [runnable];

// We can specify what resources are requested by each task.
const resources = new batch.ComputeResource();
resources.cpuMilli = 2000; // in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
resources.memoryMib = 16;
task.computeResource = resources;

task.maxRetryCount = 2;
task.maxRunDuration = {seconds: 3600};

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup();
group.taskCount = 4;
group.taskSpec = task;

// Policies are used to define on what kind of virtual machines the tasks will run on.
// In this case, we tell the system to use "e2-standard-4" machine type.
// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
const allocationPolicy = new batch.AllocationPolicy();
const policy = new batch.AllocationPolicy.InstancePolicy();
policy.machineType = 'e2-standard-4';
const instances = new batch.AllocationPolicy.InstancePolicyOrTemplate();
instances.policy = policy;
allocationPolicy.instances = [instances];

const job = new batch.Job();
job.name = jobName;
job.taskGroups = [group];
job.allocationPolicy = allocationPolicy;
job.labels = {env: 'testing', type: 'container'};
// We use Cloud Logging as it's an option available out of the box
job.logsPolicy = new batch.LogsPolicy();
job.logsPolicy.destination = batch.LogsPolicy.Destination.CLOUD_LOGGING;

// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateJob() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

  // Run request
  const response = await batchClient.createJob(request);
  console.log(response);
}

callCreateJob();

Python

Python

如需了解详情,请参阅 Batch Python API 参考文档

如需向 Batch 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import batch_v1

def create_container_job(project_id: str, region: str, job_name: str) -> batch_v1.Job:
    """
    This method shows how to create a sample Batch Job that will run
    a simple command inside a container on Cloud Compute instances.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
        job_name: the name of the job that will be created.
            It needs to be unique for each project and region pair.

    Returns:
        A job object representing the job created.
    """
    client = batch_v1.BatchServiceClient()

    # Define what will be done as part of the job.
    runnable = batch_v1.Runnable()
    runnable.container = batch_v1.Runnable.Container()
    runnable.container.image_uri = "gcr.io/google-containers/busybox"
    runnable.container.entrypoint = "/bin/sh"
    runnable.container.commands = ["-c", "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."]

    # Jobs can be divided into tasks. In this case, we have only one task.
    task = batch_v1.TaskSpec()
    task.runnables = [runnable]

    # We can specify what resources are requested by each task.
    resources = batch_v1.ComputeResource()
    resources.cpu_milli = 2000  # in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
    resources.memory_mib = 16  # in MiB
    task.compute_resource = resources

    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    # Tasks are grouped inside a job using TaskGroups.
    # Currently, it's possible to have only one task group.
    group = batch_v1.TaskGroup()
    group.task_count = 4
    group.task_spec = task

    # Policies are used to define on what kind of virtual machines the tasks will run on.
    # In this case, we tell the system to use "e2-standard-4" machine type.
    # Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "e2-standard-4"
    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy
    allocation_policy = batch_v1.AllocationPolicy()
    allocation_policy.instances = [instances]

    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy
    job.labels = {"env": "testing", "type": "container"}
    # We use Cloud Logging as it's an out of the box available option
    job.logs_policy = batch_v1.LogsPolicy()
    job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING

    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

创建基本脚本作业

您可以使用 Google Cloud 控制台、gcloud CLI、Batch API、Go、Java、Node.js 或 Python 创建基本脚本作业。

控制台

如需使用 Google Cloud 控制台创建基本脚本作业,请执行以下操作:

  1. 在 Google Cloud 控制台中,转到作业列表页面。

    转到作业列表

  2. 点击 创建创建批量作业页面会打开。

  3. 作业名称字段中,输入作业名称。

    例如,输入 example-basic-job

  4. 区域字段中,为此作业选择位置

    例如,选择 us-central1 (Iowa)(默认)。

  5. 可用区字段中,执行以下操作之一:

    • 如果您希望将此作业限制为仅在特定可用区运行,请选择一个可用区。

    • 否则,请选择 any

    例如,选择 any(默认)。

  6. 虚拟机预配模型部分,为此作业的虚拟机选择预配模型之一:

    • 如果您的作业能够承受抢占,并且您希望使用打折的虚拟机,请选择 Spot

    • 否则,请选择标准

    例如,选择标准(默认)。

  7. 选择以下机器系列之一:

    • 对于常见工作负载,请点击通用

    • 对于性能密集型的工作负载,点击计算优化

    • 对于内存密集型工作负载,请点击内存优化

    例如,点击通用(默认)。

  8. 系列字段中,为此作业的虚拟机选择一个机器系列

    例如,如果您为机器系列选择了通用,请选择 E2(默认)。

  9. 机器类型字段中,为此作业的虚拟机选择机器类型。

    例如,如果您为机器系列选择了 E2,请选择 e2-medium(2 个 vCPU,4 GB 内存)(默认)。

  10. New runnable 窗格中,执行以下操作:

    1. 选择脚本。系统会显示一个文本框。

    2. 在文本框中,输入要为此作业中的每个任务运行的脚本。

      例如,输入以下脚本:

      echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.
      
    3. 点击完成

  11. 任务数字段中,输入此作业的任务数。该值必须是介于 110000 之间的整数。

    例如,输入 4

  12. 并行处理字段中,输入要并发运行的任务数量。此数字不能大于任务总数,并且必须是 11000 之间的整数。

    例如,输入 2

  13. 任务资源部分,通过执行以下操作来指定每项任务所需的虚拟机资源量:

    1. 核心数字段中,输入 vCPU 的数量。

      例如,输入 1(默认值)。

    2. 内存字段中,输入 RAM 量(以 GB 为单位)。

      例如,输入 0.5(默认值)。

  14. 点击创建

作业列表页面会显示您创建的作业。

gcloud

如需使用 gcloud CLI 创建基本脚本作业,请执行以下操作:

  1. 创建一个用于指定作业的配置详情的 JSON 文件。例如,如需创建基本脚本作业,请创建包含以下内容的 JSON 文件。如需详细了解可以为作业指定的所有字段,请参阅 projects.locations.jobs REST 资源的参考文档。

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                SCRIPT
                            }
                        }
                    ],
                    "computeResource": {
                        "cpuMilli": CORES,
                        "memoryMib": MEMORY
                    },
                    "maxRetryCount": MAX_RETRY_COUNT,
                    "maxRunDuration": "MAX_RUN_DURATION"
                },
                "taskCount": TASK_COUNT,
                "parallelism": PARALLELISM
            }
        ]
    }
    

    请替换以下内容:

    • SCRIPT:每个任务运行的脚本
    • CORES:可选。要分配给每个任务的核心数量(具体来讲,就是 vCPU),通常代表半个物理核心,单位为毫安单位。如果未指定 cpuMilli 字段,则将该值设置为 2000(2 个 vCPU)。
    • MEMORY:可选。为每个任务分配的内存容量(以 MB 为单位)。如果未指定 memoryMib 字段,则将该值设置为 2000 (2 GB)。
    • MAX_RETRY_COUNT:可选。任务的重试次数上限。该值必须是介于 010 之间的整数。如果未指定 maxRetryCount 字段,则将该值设置为 0,这意味着不会重试任务。
    • MAX_RUN_DURATION:可选。允许任务在重试或失败之前运行的最长时间,格式为以秒为单位的值,后跟 s。如果未指定 maxRunDuration 字段,则该值将设置为 604800s(7 天),这是最大值。
    • TASK_COUNT:可选。作业的任务数。该值必须是介于 110000 之间的整数。如果未指定 taskCount 字段,则将该值设置为 1
    • PARALLELISM:可选。作业并发运行的任务数。该数字不能大于任务数,并且必须是 11000 之间的整数。如果未指定 parallelism 字段,则将该值设置为 1
  2. 使用 gcloud batch jobs submit 命令创建作业。

    gcloud batch jobs submit JOB_NAME \
      --location LOCATION \
      --config JSON_CONFIGURATION_FILE
    

    请替换以下内容:

    • JOB_NAME:作业的名称。
    • LOCATION:作业的位置
    • JSON_CONFIGURATION_FILE:包含作业配置详细信息的 JSON 文件的路径。

例如,如需使用脚本创建运行任务的作业,请执行以下操作:

  1. 在当前目录中创建一个名为 hello-world-script.json 且包含以下内容的 JSON 文件:

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                            }
                        }
                    ],
                    "computeResource": {
                        "cpuMilli": 2000,
                        "memoryMib": 16
                    },
                    "maxRetryCount": 2,
                    "maxRunDuration": "3600s"
                },
                "taskCount": 4,
                "parallelism": 2
            }
        ],
        "allocationPolicy": {
            "instances": [
                {
                    "policy": { "machineType": "e2-standard-4" }
                }
            ]
        },
        "labels": {
            "department": "finance",
            "env": "testing"
        },
        "logsPolicy": {
            "destination": "CLOUD_LOGGING"
        }
    }
    
  2. 运行以下命令:

    gcloud batch jobs submit example-script-job \
      --location us-central1 \
      --config hello-world-script.json
    

API

如需使用 Batch API 创建基本的脚本作业,请使用 jobs.create 方法。如需详细了解可以为作业指定的所有字段,请参阅 projects.locations.jobs REST 资源的参考文档。

POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs?job_id=JOB_NAME

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            SCRIPT
                        }
                    }
                ],
                "computeResource": {
                    "cpuMilli": CORES,
                    "memoryMib": MEMORY
                },
                "maxRetryCount": MAX_RETRY_COUNT,
                "maxRunDuration": "MAX_RUN_DURATION"
            },
            "taskCount": TASK_COUNT,
            "parallelism": PARALLELISM
        }
    ]
}

请替换以下内容:

  • PROJECT_ID:项目的项目 ID
  • LOCATION:作业的位置
  • JOB_NAME:作业的名称。
  • SCRIPT:每个任务运行的脚本
  • CORES:可选。要分配给每个任务的核心数量(具体来讲,就是 vCPU),通常代表半个物理核心,单位为毫单位。如果未指定 cpuMilli 字段,则将该值设置为 2000(2 个 vCPU)。
  • MEMORY:可选。为每个任务分配的内存容量(以 MB 为单位)。如果未指定 memoryMib 字段,则将该值设置为 2000 (2 GB)。
  • MAX_RETRY_COUNT:可选。任务的重试次数上限。该值必须是介于 010 之间的整数。如果未指定 maxRetryCount 字段,则将该值设置为 0,这意味着不会重试任务。
  • MAX_RUN_DURATION:可选。重试或失败之前允许任务运行的最长时间,格式为秒,后跟 s。如果未指定 maxRunDuration 字段,则该值将设置为 604800s(7 天),这是最大值。
  • TASK_COUNT:可选。作业的任务数。该值必须是介于 110000 之间的整数。如果未指定 taskCount 字段,则将该值设置为 1
  • PARALLELISM:可选。作业并发运行的任务数。该数字不能大于任务数,并且必须是 11000 之间的整数。如果未指定 parallelism 字段,则将该值设置为 1

例如,如需创建使用脚本运行任务的作业,请使用以下请求:

POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/jobs?job_id=example-script-job

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            "text": "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                        }
                    }
                ],
                "computeResource": {
                    "cpuMilli": 2000,
                    "memoryMib": 16
                },
                "maxRetryCount": 2,
                "maxRunDuration": "3600s"
            },
            "taskCount": 4,
            "parallelism": 2
        }
    ],
    "allocationPolicy": {
        "instances": [
            {
                "policy": { "machineType": "e2-standard-4" }
            }
        ]
    },
    "labels": {
        "department": "finance",
        "env": "testing"
    },
    "logsPolicy": {
        "destination": "CLOUD_LOGGING"
    }
}

其中 PROJECT_ID 是项目的项目 ID

Go

Go

如需了解详情,请参阅 Batch Go API 参考文档

如需向 Batch 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
	durationpb "google.golang.org/protobuf/types/known/durationpb"
)

// Creates and runs a job that executes the specified script
func createScriptJob(w io.Writer, projectID, region, jobName string) error {
	// projectID := "your_project_id"
	// region := "us-central1"
	// jobName := "some-job"

	ctx := context.Background()
	batchClient, err := batch.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer batchClient.Close()

	// Define what will be done as part of the job.
	command := &batchpb.Runnable_Script_Text{
		Text: "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.",
	}
	// You can also run a script from a file. Just remember, that needs to be a script that's
	// already on the VM that will be running the job.
	// Using runnable.script.text and runnable.script.path is mutually exclusive.
	// command := &batchpb.Runnable_Script_Path{
	// 	Path: "/tmp/test.sh",
	// }

	// We can specify what resources are requested by each task.
	resources := &batchpb.ComputeResource{
		// CpuMilli is milliseconds per cpu-second. This means the task requires 2 whole CPUs.
		CpuMilli:  2000,
		MemoryMib: 16,
	}

	taskSpec := &batchpb.TaskSpec{
		Runnables: []*batchpb.Runnable{{
			Executable: &batchpb.Runnable_Script_{
				Script: &batchpb.Runnable_Script{Command: command},
			},
		}},
		ComputeResource: resources,
		MaxRunDuration: &durationpb.Duration{
			Seconds: 3600,
		},
		MaxRetryCount: 2,
	}

	// Tasks are grouped inside a job using TaskGroups.
	taskGroups := []*batchpb.TaskGroup{
		{
			TaskCount: 4,
			TaskSpec:  taskSpec,
		},
	}

	// Policies are used to define on what kind of virtual machines the tasks will run on.
	// In this case, we tell the system to use "e2-standard-4" machine type.
	// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
	allocationPolicy := &batchpb.AllocationPolicy{
		Instances: []*batchpb.AllocationPolicy_InstancePolicyOrTemplate{{
			PolicyTemplate: &batchpb.AllocationPolicy_InstancePolicyOrTemplate_Policy{
				Policy: &batchpb.AllocationPolicy_InstancePolicy{
					MachineType: "e2-standard-4",
				},
			},
		}},
	}

	// We use Cloud Logging as it's an out of the box available option
	logsPolicy := &batchpb.LogsPolicy{
		Destination: batchpb.LogsPolicy_CLOUD_LOGGING,
	}

	jobLabels := map[string]string{"env": "testing", "type": "script"}

	// The job's parent is the region in which the job will run
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, region)

	job := batchpb.Job{
		TaskGroups:       taskGroups,
		AllocationPolicy: allocationPolicy,
		Labels:           jobLabels,
		LogsPolicy:       logsPolicy,
	}

	req := &batchpb.CreateJobRequest{
		Parent: parent,
		JobId:  jobName,
		Job:    &job,
	}

	created_job, err := batchClient.CreateJob(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create job: %w", err)
	}

	fmt.Fprintf(w, "Job created: %v\n", created_job)

	return nil
}

Java

Java

如需了解详情,请参阅 Batch Java API 参考文档

如需向 Batch 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.batch.v1.AllocationPolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicyOrTemplate;
import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.ComputeResource;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.LogsPolicy.Destination;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.Runnable.Script;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateWithScriptNoMounting {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the region you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "europe-central2";

    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "JOB_NAME";

    createScriptJob(projectId, region, jobName);
  }

  // This method shows how to create a sample Batch Job that will run
  // a simple command on Cloud Compute instances.
  public static void createScriptJob(String projectId, String region, String jobName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `batchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      // Define what will be done as part of the job.
      Runnable runnable =
          Runnable.newBuilder()
              .setScript(
                  Script.newBuilder()
                      .setText(
                          "echo Hello world! This is task ${BATCH_TASK_INDEX}. "
                              + "This job has a total of ${BATCH_TASK_COUNT} tasks.")
                      // You can also run a script from a file. Just remember, that needs to be a
                      // script that's already on the VM that will be running the job.
                      // Using setText() and setPath() is mutually exclusive.
                      // .setPath("/tmp/test.sh")
                      .build())
              .build();

      // We can specify what resources are requested by each task.
      ComputeResource computeResource =
          ComputeResource.newBuilder()
              // In milliseconds per cpu-second. This means the task requires 2 whole CPUs.
              .setCpuMilli(2000)
              // In MiB.
              .setMemoryMib(16)
              .build();

      TaskSpec task =
          TaskSpec.newBuilder()
              // Jobs can be divided into tasks. In this case, we have only one task.
              .addRunnables(runnable)
              .setComputeResource(computeResource)
              .setMaxRetryCount(2)
              .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
              .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder().setTaskCount(4).setTaskSpec(task).build();

      // Policies are used to define on what kind of virtual machines the tasks will run on.
      // In this case, we tell the system to use "e2-standard-4" machine type.
      // Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
      InstancePolicy instancePolicy =
          InstancePolicy.newBuilder().setMachineType("e2-standard-4").build();

      AllocationPolicy allocationPolicy =
          AllocationPolicy.newBuilder()
              .addInstances(InstancePolicyOrTemplate.newBuilder().setPolicy(instancePolicy).build())
              .build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              .setAllocationPolicy(allocationPolicy)
              .putLabels("env", "testing")
              .putLabels("type", "script")
              // We use Cloud Logging as it's an out of the box available option.
              .setLogsPolicy(
                  LogsPolicy.newBuilder().setDestination(Destination.CLOUD_LOGGING).build())
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.getName());
    }
  }
}

Node.js

Node.js

如需了解详情,请参阅 Batch Node.js API 参考文档

如需向 Batch 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
/**
 * The region you want to the job to run in. The regions that support Batch are listed here:
 * https://cloud.google.com/batch/docs/get-started#locations
 */
// const region = 'us-central-1';
/**
 * The name of the job that will be created.
 * It needs to be unique for each project and region pair.
 */
// const jobName = 'YOUR_JOB_NAME';

// Imports the Batch library
const batchLib = require('@google-cloud/batch');
const batch = batchLib.protos.google.cloud.batch.v1;

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

// Define what will be done as part of the job.
const task = new batch.TaskSpec();
const runnable = new batch.Runnable();
runnable.script = new batch.Runnable.Script();
runnable.script.text =
  'echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.';
// You can also run a script from a file. Just remember, that needs to be a script that's
// already on the VM that will be running the job. Using runnable.script.text and runnable.script.path is mutually
// exclusive.
// runnable.script.path = '/tmp/test.sh'
task.runnables = [runnable];

// We can specify what resources are requested by each task.
const resources = new batch.ComputeResource();
resources.cpuMilli = 2000; // in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
resources.memoryMib = 16;
task.computeResource = resources;

task.maxRetryCount = 2;
task.maxRunDuration = {seconds: 3600};

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup();
group.taskCount = 4;
group.taskSpec = task;

// Policies are used to define on what kind of virtual machines the tasks will run on.
// In this case, we tell the system to use "e2-standard-4" machine type.
// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
const allocationPolicy = new batch.AllocationPolicy();
const policy = new batch.AllocationPolicy.InstancePolicy();
policy.machineType = 'e2-standard-4';
const instances = new batch.AllocationPolicy.InstancePolicyOrTemplate();
instances.policy = policy;
allocationPolicy.instances = [instances];

const job = new batch.Job();
job.name = jobName;
job.taskGroups = [group];
job.allocationPolicy = allocationPolicy;
job.labels = {env: 'testing', type: 'script'};
// We use Cloud Logging as it's an option available out of the box
job.logsPolicy = new batch.LogsPolicy();
job.logsPolicy.destination = batch.LogsPolicy.Destination.CLOUD_LOGGING;

// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateJob() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

  // Run request
  const response = await batchClient.createJob(request);
  console.log(response);
}

callCreateJob();

Python

Python

如需了解详情,请参阅 Batch Python API 参考文档

如需向 Batch 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import batch_v1

def create_script_job(project_id: str, region: str, job_name: str) -> batch_v1.Job:
    """
    This method shows how to create a sample Batch Job that will run
    a simple command on Cloud Compute instances.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
        job_name: the name of the job that will be created.
            It needs to be unique for each project and region pair.

    Returns:
        A job object representing the job created.
    """
    client = batch_v1.BatchServiceClient()

    # Define what will be done as part of the job.
    task = batch_v1.TaskSpec()
    runnable = batch_v1.Runnable()
    runnable.script = batch_v1.Runnable.Script()
    runnable.script.text = "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
    # You can also run a script from a file. Just remember, that needs to be a script that's
    # already on the VM that will be running the job. Using runnable.script.text and runnable.script.path is mutually
    # exclusive.
    # runnable.script.path = '/tmp/test.sh'
    task.runnables = [runnable]

    # We can specify what resources are requested by each task.
    resources = batch_v1.ComputeResource()
    resources.cpu_milli = 2000  # in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
    resources.memory_mib = 16
    task.compute_resource = resources

    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    # Tasks are grouped inside a job using TaskGroups.
    # Currently, it's possible to have only one task group.
    group = batch_v1.TaskGroup()
    group.task_count = 4
    group.task_spec = task

    # Policies are used to define on what kind of virtual machines the tasks will run on.
    # In this case, we tell the system to use "e2-standard-4" machine type.
    # Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
    allocation_policy = batch_v1.AllocationPolicy()
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "e2-standard-4"
    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy
    allocation_policy.instances = [instances]

    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy
    job.labels = {"env": "testing", "type": "script"}
    # We use Cloud Logging as it's an out of the box available option
    job.logs_policy = batch_v1.LogsPolicy()
    job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING

    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

使用环境变量

当您编写希望作业运行的容器映像或脚本时,请使用环境变量。您可以使用为所有批处理作业预定义的任何环境变量,以及创建作业时定义的任何自定义环境变量。

使用预定义环境变量

默认情况下,作业中的可运行函数可以使用以下预定义环境变量:

  • BATCH_TASK_COUNT:任务组中的任务数量。
  • BATCH_TASK_INDEX:任务组中任务的索引编号。索引编号从 0 开始。
  • BATCH_HOSTS_FILE:可选。列出任务组中所有正在运行的虚拟机实例的文件的路径。如需使用此环境变量,requireHostsFile 字段为必填字段,并且必须设置为 true。

有关如何使用预定义环境变量的示例,请参阅本文档中创建基本作业中的之前可运行示例。

定义和使用自定义环境变量

(可选)您可以为作业中的一个或多个可运行对象定义以下类型的自定义环境变量:

  • 一个可运行的变量,该变量具有运行该可运行的所有任务的
  • 一个可运行的数组,其中的每个任务都有一个值来运行。

本部分举例说明了如何创建用于定义和使用自定义环境变量的两个作业。第一个示例作业将环境变量传递到每个任务运行的可运行对象。第二个示例作业将一个环境变量数组(具有匹配名称但值不同)传递给任务,这些任务的索引与数组中环境变量的索引匹配。

本部分介绍如何使用 gcloud CLI 或 Batch API 为您的作业定义和使用自定义环境变量。

gcloud

如果您要定义一个作业,将环境变量传递给每个任务运行的可运行对象,请参阅有关如何为可运行对象定义和使用环境变量的示例。否则,如果您想定义一个作业,根据任务索引将环境变量列表传递给不同的任务,请参阅有关如何为每个任务定义和使用环境变量的示例。

为 Runnable 定义和使用环境变量

如需使用 gcloud CLI 将环境变量传递给可运行的作业,请使用 gcloud batch jobs submit 命令,并在作业的配置文件中指定环境变量。

例如,如需创建一个定义了环境变量的脚本作业,并将其传递给包含 3 项任务的脚本,请发出以下请求:

  1. 在当前目录中创建一个名为 hello-world-environment-variables.json 且包含以下内容的 JSON 文件:

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello ${VARIABLE_NAME}! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                            },
                            "environment": {
                                "variables": {
                                    "VARIABLE_NAME": "VARIABLE_VALUE"
                                }
                            }
                        }
                    ],
                    "computeResource": {
                        "cpuMilli": 2000,
                        "memoryMib": 16
                    }
                },
                "taskCount": 3,
                "parallelism": 1
            }
        ],
        "allocationPolicy": {
            "instances": [
                {
                    "policy": {
                        "machineType": "e2-standard-4"
                    }
                }
            ]
        }
    }
    

    请替换以下内容:

    • VARIABLE_NAME:传递给每个任务的环境变量的名称。按照惯例,环境变量名称会大写
    • VARIABLE_VALUE:可选。传递给每个任务的环境变量的值。
  2. 运行以下命令:

    gcloud batch jobs submit example-environment-variables-job \
      --location us-central1 \
      --config hello-world-environment-variables.json
    

为每个任务定义和使用环境变量

如需使用 gcloud CLI 根据任务索引将环境变量传递给任务的作业,请使用 gcloud batch jobs submit 命令,并在作业的配置文件中指定 taskEnvironments 数组字段。

例如,如需创建包含 3 个环境变量(由匹配名称和不同值组成)的作业,并将环境变量传递给任务的脚本,因此任务的脚本应与数组中的环境变量索引匹配:

  1. 在当前目录中创建一个名为 hello-world-task-environment-variables.json 且包含以下内容的 JSON 文件:

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello ${TASK_VARIABLE_NAME}! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                            },
                        }
                    ],
                    "computeResource": {
                        "cpuMilli": 2000,
                        "memoryMib": 16
                    }
                },
                "taskCount": 3,
                "taskEnvironments": [
                    {
                        "variables": {
                            "TASK_VARIABLE_NAME": "TASK_VARIABLE_VALUE_0"
                        }
                    },
                    {
                        "variables": {
                            "TASK_VARIABLE_NAME": "TASK_VARIABLE_VALUE_1"
                        }
                    },
                    {
                        "variables": {
                            "TASK_VARIABLE_NAME": "TASK_VARIABLE_VALUE_2"
                        }
                    }
                ]
            }
        ],
        "allocationPolicy": {
            "instances": [
                {
                    "policy": {
                        "machineType": "e2-standard-4"
                    }
                }
            ]
        }
    }
    

    请替换以下内容:

    • TASK_VARIABLE_NAME:传递给具有匹配索引的任务的任务环境变量的名称。按照惯例,环境变量名称会大写
    • TASK_VARIABLE_VALUE_0:传递给任务的环境变量的值,BATCH_TASK_INDEX 等于 0
    • TASK_VARIABLE_VALUE_1:传递给任务的环境变量的值,BATCH_TASK_INDEX 等于 1
    • TASK_VARIABLE_VALUE_2:传递给任务的环境变量的值,BATCH_TASK_INDEX 等于 2
  2. 运行以下命令:

    gcloud batch jobs submit example-task-environment-variables-job \
      --location us-central1 \
      --config hello-world-task-environment-variables.json
    

API

如果您要定义一个作业,将环境变量传递给每个任务运行的可运行对象,请参阅有关如何为可运行对象定义和使用环境变量的示例。否则,如果您想定义一个作业,根据任务索引将环境变量列表传递给不同的任务,请参阅有关如何为每个任务定义和使用环境变量的示例。

为 Runnable 定义和使用环境变量

如需使用 Batch API 创建将环境变量传递给可运行的作业,请使用 gcloud batch jobs submit 命令,并在 environment 字段中指定环境变量。

例如,如需创建包含环境变量的作业并将其传递给包含 3 个任务的脚本,请发出以下请求:

POST https://batch.googleapis.com/v1/projects/<var>PROJECT_ID</var>/locations/us-central1/jobs?job_id=example-environment-variables-job

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            "text": "echo Hello ${VARIABLE_NAME}! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                        },
                        "environment": {
                            "variables": {
                                "VARIABLE_NAME": "VARIABLE_VALUE"
                            }
                        }
                    }
                ],
                "computeResource": {
                    "cpuMilli": 2000,
                    "memoryMib": 16
                }
            },
            "taskCount": 3,
            "parallelism": 1
        }

    ],
    "allocationPolicy": {
        "instances": [
            {
                "policy": {
                    "machineType": "e2-standard-4"
                }
            }
        ]
    }
}

请替换以下内容:

  • PROJECT_ID:项目的项目 ID
  • VARIABLE_NAME:传递给每个任务的环境变量的名称。按照惯例,环境变量名称会大写
  • VARIABLE_VALUE:传递给每个任务的环境变量的值。

为每个任务定义和使用环境变量

如需使用 Batch API 根据任务索引将环境变量传递给任务的作业,请使用 jobs.create 方法,并在 taskEnvironments 数组字段中指定环境变量。

例如,如需创建包含 3 个环境变量(由匹配名称和不同值组成)的作业,并根据环境变量的索引将任务传递给 3 个任务的脚本,可发出以下请求:

POST https://batch.googleapis.com/v1/projects/<var>PROJECT_ID</var>/locations/us-central1/jobs?job_id=example-task-environment-variables-job

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            "text": "echo Hello ${TASK_VARIABLE_NAME}! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                        },
                    }
                ],
                "computeResource": {
                    "cpuMilli": 2000,
                    "memoryMib": 16
                }
            },
            "taskCount": 3,
            "taskEnvironments": [
                {
                    "variables": {
                        "TASK_VARIABLE_NAME": "TASK_VARIABLE_VALUE_0"
                    }
                },
                {
                    "variables": {
                        "TASK_VARIABLE_NAME": "TASK_VARIABLE_VALUE_1"
                    }
                },
                {
                    "variables": {
                        "TASK_VARIABLE_NAME": "TASK_VARIABLE_VALUE_2"
                    }
                }
            ]
        }
    ],
    "allocationPolicy": {
        "instances": [
            {
                "policy": { "machineType": "e2-standard-4" }
            }
        ]
    }
}

请替换以下内容:

  • PROJECT_ID:项目的项目 ID
  • TASK_VARIABLE_NAME:传递到具有匹配索引的任务的环境变量的名称。按照惯例,环境变量名称会大写
  • TASK_VARIABLE_VALUE_0:传递给任务的环境变量的值,BATCH_TASK_INDEX 等于 0
  • TASK_VARIABLE_VALUE_1:传递给任务的环境变量的值,BATCH_TASK_INDEX 等于 1
  • TASK_VARIABLE_VALUE_2:传递给任务的环境变量的值,BATCH_TASK_INDEX 等于 2

后续步骤