기본 작업 만들기 및 실행

이 문서에서는 Batch 작업 만들기의 기초와 스크립트 또는 컨테이너 이미지를 기반으로 작업을 만들어서 실행하고 사전 정의된 변수 및 커스텀 변수를 사용하는 방법을 설명합니다. 작업 만들기 및 실행에 대한 자세한 내용은 작업 만들기 및 실행 개요를 참조하세요.

시작하기 전에

  • Batch를 사용한 적이 없으면 Batch 시작하기를 검토하고 프로젝트 및 사용자 기본 요건을 완료하여 Batch를 사용 설정하세요.
  • 작업을 생성하는 데 필요한 권한을 얻으려면 관리자에게 다음 IAM 역할을 부여해 달라고 요청하세요.

    역할 부여에 대한 자세한 내용은 액세스 관리를 참조하세요.

    커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

  • 작업을 만들 때마다 작업에 유효한 네트워크 구성이 있는지 확인하세요.
    • 워크로드 또는 프로젝트에 대한 특정 네트워킹 요구사항이 없고 프로젝트의 기본 네트워크를 수정하지 않은 경우 별도의 조치를 취할 필요가 없습니다.
    • 그렇지 않으면 작업을 만들 때 네트워킹을 구성해야 합니다. 기본 작업을 만들기 전에 작업의 네트워킹을 구성하여 네트워킹 요구사항을 충족하도록 아래 예시를 수정하는 방법을 알아보세요.
    작업의 네트워크 구성에 대한 자세한 내용은 일괄 네트워킹 개요를 참조하세요.
  • 작업을 만들 때마다 작업에 유효한 VM 운영체제(OS) 환경이 있는지 확인합니다.
    • 워크로드 또는 프로젝트에 대한 특정 VM OS 이미지 또는 부팅 디스크 요구사항이 없는 경우 별도의 조치를 취할 필요가 없습니다.
    • 그렇지 않으면 유효한 VM OS 환경 옵션을 준비해야 합니다. 기본 작업을 만들기 전에 VM OS 환경의 기본 구성을 허용하거나, 요구사항에 맞게 아래 예시를 수정하여 VM OS 환경을 맞춤설정하는 방법을 알아보세요.
    작업의 VM OS 환경에 대한 자세한 내용은 VM OS 환경 개요를 참조하세요.

기본 작업 만들기

작업에 지정할 수 있는 모든 필드에 대한 자세한 내용은 참조 문서에서 projects.locations.jobs REST 리소스를 참조하세요. 간단히 말해서 작업은 작업에 대한 실행 가능한 스크립트 또는 컨테이너에 해당하는 실행 가능 항목을 하나 이상 실행하는 하나 이상의 태스크 배열로 구성되어 있습니다. 기본 사항을 설명하기 위해 이 섹션에서는 스크립트 또는 컨테이너 이미지에 해당하는 실행 가능 항목을 하나만 사용해서 예시 작업을 만드는 방법을 설명합니다.

  • Batch를 사용해서 컨테이너 이미지를 실행하는 작업을 작성하려면 컨테이너 작업 만들기를 참조하세요.
  • 컨테이너 이미지를 사용할지 여부가 확실하지 않거나 컨테이너에 익숙하지 않은 경우 스크립트 작업을 만드는 것이 좋습니다.

두 유형의 작업 예시 모두 4개의 태스크 배열이 있는 태스크 그룹이 포함되어 있습니다. 각 태스크는 메시지 및 해당 색인을 표준 출력과 Cloud Logging에 출력합니다. 이 작업의 정의는 2개의 동시 로드를 지정하며, 이는 한 번에 2개의 태스크가 실행될 수 있도록 작업을 2개의 VM에서 실행해야 한다는 것을 나타냅니다.

기본 컨테이너 작업 만들기

모든 컴퓨팅 환경에서 실행할 수 있도록 작업에 대해 코드 및 종속 항목을 제공하기 위해 컨테이너 이미지를 선택하거나 만들 수 있습니다. 자세한 내용은 컨테이너 이미지 작업VM 인스턴스에서 컨테이너 실행을 참조하세요.

Google Cloud 콘솔, gcloud CLI, Batch API, Go, Java, Node.js, Python 또는 C++을 사용하여 기본 컨테이너 작업을 만들 수 있습니다.

콘솔

Google Cloud 콘솔을 사용하여 기본 컨테이너 작업을 만들려면 다음을 수행합니다.

  1. Google Cloud 콘솔에서 작업 목록 페이지로 이동합니다.

    작업 목록으로 이동

  2. 만들기를 클릭합니다. 일괄 작업 만들기 페이지가 열립니다. 왼쪽 창에서 작업 세부정보 페이지가 선택됩니다.

  3. 작업 세부정보 페이지를 구성합니다.

    1. 선택 사항: 작업 이름 필드에서 작업 이름을 맞춤설정합니다.

      예를 들어 example-basic-job를 입력합니다.

    2. 태스크 세부정보 섹션을 구성합니다.

      1. 새 실행 가능 항목 창에서 이 작업을 실행할 스크립트 또는 컨테이너를 하나 이상 추가합니다.

        예를 들어 컨테이너 하나를 추가하려면 다음을 수행합니다.

        1. 컨테이너 이미지 URL(기본값)을 선택합니다.

        2. 컨테이너 이미지 URL 필드에 이 작업의 각 태스크에서 실행할 컨테이너 이미지의 URL을 입력합니다.

          예를 들어 busybox Docker 컨테이너 이미지를 사용하려면 다음 URL을 입력합니다.

          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.
            
          3. 완료를 클릭합니다.

      2. 태스크 수 필드에 이 작업의 태스크 수를 입력합니다. 이 값은 1태스크 그룹당 태스크 한도 사이의 정수여야 합니다.

        예를 들어 4를 입력합니다.

      3. 동시 실행 필드에 동시에 실행할 작업 수를 입력합니다. 이 수는 총 태스크 수보다 클 수 없으며 1작업당 동시 태스크 한도 사이의 정수여야 합니다.

        예를 들어 2를 입력합니다.

  4. 리소스 사양 페이지를 구성합니다.

    1. 왼쪽 창에서 리소스 사양을 클릭합니다. 리소스 사양 페이지가 열립니다.

    2. VM 프로비저닝 모델 섹션에서 이 작업의 VM에 대한 프로비저닝 모델에 대해 다음 옵션 중 하나를 선택합니다.

      • 작업이 선점을 감내할 수 있고 할인된 가격으로 VM을 사용하려면 Spot을 선택합니다.

      • 그렇지 않으면 표준을 선택합니다.

      예를 들어 표준(기본값)을 선택합니다.

    3. 이 작업의 위치를 선택합니다.

      1. 리전 필드에서 리전을 선택합니다.

        예를 들어 us-central1 (Iowa)(기본값)을 선택합니다.

      2. 영역 필드에서 다음 중 하나를 수행합니다.

        • 이 작업이 특정 영역에서만 실행되도록 제한하려면 영역을 선택합니다.

        • 그렇지 않으면 모두를 선택합니다.

        예를 들어 모두(기본값)를 선택합니다.

    4. 다음 머신 계열 중 하나를 선택합니다.

      • 일반적인 워크로드의 경우 범용을 클릭합니다.

      • 성능 집약적인 워크로드의 경우 컴퓨팅 최적화를 클릭합니다.

      • 메모리 집약적인 워크로드의 경우 메모리 최적화를 클릭합니다.

      예를 들어 범용(기본값)을 클릭합니다.

    5. 계열 필드에서 이 작업의 VM에 대한 머신 계열을 선택합니다.

      예를 들어 머신 계열에 범용을 선택한 경우 E2(기본값)를 선택합니다.

    6. 머신 유형 필드에서 이 작업의 VM에 대한 머신 유형을 선택합니다.

      예를 들어 머신 계열에서 E2를 선택한 경우 e2-medium(vCPU 2개, 메모리 4GB)(기본값)을 선택합니다.

    7. 각 태스크에 필요한 VM 리소스 양을 구성합니다.

      1. 코어 필드에 태스크당 vCPU 양을 입력합니다.

        예를 들어 1(기본값)을 입력합니다.

      2. 메모리 필드에 태스크당 RAM의 크기를 GB 단위로 입력합니다.

        예를 들어 0.5(기본값)을 입력합니다.

  5. 선택사항: 작업 구성을 검토하려면 왼쪽 창에서 미리보기를 클릭합니다.

  6. 만들기를 클릭합니다.

작업 세부정보 페이지에 자신이 만든 작업이 표시됩니다.

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: (선택사항) 각 태스크에 할당할 milliCPU 단위의 코어(특히 물리적 코어의 절반을 나타내는 vCPU)의 수입니다. cpuMilli 필드가 지정되지 않은 경우 값은 2000(vCPU 2개)으로 설정됩니다.
    • MEMORY: 선택사항. 각 태스크에 할당할 메모리 양(MB). memoryMib 필드가 지정되지 않은 경우 값은 2000(2GB)으로 설정됩니다.
    • MAX_RETRY_COUNT: 선택사항. 태스크의 최대 재시도 횟수입니다. 값은 0에서 10 사이의 정수여야 합니다. maxRetryCount 필드가 지정되지 않은 경우 값은 0으로 설정됩니다. 즉, 태스크를 다시 시도하지 않습니다. maxRetryCount 필드에 대한 자세한 내용은 태스크 재시도 자동화를 참조하세요.
    • MAX_RUN_DURATION: 선택사항. 재시도 또는 실패 전에 태스크가 실행될 수 있는 최대 시간은 뒤에 s가 있는 초 단위의 값으로 형식이 지정됩니다(예: 1시간의 경우 3600s). maxRunDuration 필드를 지정하지 않으면 값이 작업의 최대 실행 시간으로 설정됩니다. maxRunDuration 필드에 대한 자세한 내용은 제한 시간을 사용하여 태스크 및 실행 가능 항목의 실행 시간 제한을 참조하세요.
    • TASK_COUNT: 선택사항. 작업의 태스크 수. 이 값은 1태스크 그룹당 태스크 한도 사이의 정수여야 합니다. taskCount 필드를 지정하지 않으면 값이 1로 설정됩니다.
    • PARALLELISM: (선택사항) 작업이 동시에 실행하는 태스크 수입니다. 이 수는 태스크 수보다 클 수 없으며 1작업당 동시 태스크 한도 사이의 정수여야 합니다. 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: (선택사항) 각 태스크에 할당할 milliCPU 단위의 코어(특히 물리적 코어의 절반을 나타내는 vCPU)의 수입니다. cpuMilli 필드가 지정되지 않은 경우 값은 2000(vCPU 2개)으로 설정됩니다.
  • MEMORY: 선택사항. 각 태스크에 할당할 메모리 양(MB). memoryMib 필드가 지정되지 않은 경우 값은 2000(2GB)으로 설정됩니다.
  • MAX_RETRY_COUNT: 선택사항. 태스크의 최대 재시도 횟수입니다. 값은 0에서 10 사이의 정수여야 합니다. maxRetryCount 필드가 지정되지 않은 경우 값은 0으로 설정됩니다. 즉, 태스크를 다시 시도하지 않습니다. maxRetryCount 필드에 대한 자세한 내용은 태스크 재시도 자동화를 참조하세요.
  • MAX_RUN_DURATION: 선택사항. 재시도 또는 실패 전에 태스크가 실행될 수 있는 최대 시간은 뒤에 s가 있는 초 단위의 값으로 형식이 지정됩니다(예: 1시간의 경우 3600s). maxRunDuration 필드를 지정하지 않으면 값이 작업의 최대 실행 시간으로 설정됩니다. maxRunDuration 필드에 대한 자세한 내용은 제한 시간을 사용하여 태스크 및 실행 가능 항목의 실행 시간 제한을 참조하세요.
  • TASK_COUNT: 선택사항. 작업의 태스크 수. 1에서 태스크 그룹당 태스크 한도 사이의 정수여야 합니다. taskCount 필드를 지정하지 않으면 값이 1로 설정됩니다.
  • PARALLELISM: (선택사항) 작업이 동시에 실행하는 태스크 수. 이 수는 태스크 수보다 클 수 없으며 1작업당 동시 태스크 한도 사이의 정수여야 합니다. 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)

C++

C++

자세한 내용은 Batch C++ API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

#include "google/cloud/batch/v1/batch_client.h"

  [](std::string const& project_id, std::string const& location_id,
     std::string const& job_id) {
    // Initialize the request; start with the fields that depend on the sample
    // input.
    google::cloud::batch::v1::CreateJobRequest request;
    request.set_parent("projects/" + project_id + "/locations/" + location_id);
    request.set_job_id(job_id);
    // Most of the job description is fixed in this example; use a string to
    // initialize it.
    auto constexpr kText = R"pb(
      task_groups {
        task_count: 4
        task_spec {
          compute_resource { cpu_milli: 500 memory_mib: 16 }
          max_retry_count: 2
          max_run_duration { seconds: 3600 }
          runnables {
            container {
              image_uri: "gcr.io/google-containers/busybox"
              entrypoint: "/bin/sh"
              commands: "-c"
              commands: "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
            }
          }
        }
      }
      allocation_policy {
        instances {
          policy { machine_type: "e2-standard-4" provisioning_model: STANDARD }
        }
      }
      labels { key: "env" value: "testing" }
      labels { key: "type" value: "container" }
      logs_policy { destination: CLOUD_LOGGING }
    )pb";
    auto* job = request.mutable_job();
    if (!google::protobuf::TextFormat::ParseFromString(kText, job)) {
      throw std::runtime_error("Error parsing Job description");
    }
    // Create a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    auto response = client.CreateJob(request);
    if (!response) throw std::move(response).status();
    std::cout << "Job : " << response->DebugString() << "\n";
  }

기본 스크립트 작업 만들기

Google Cloud 콘솔, gcloud CLI, Batch API, Go, Java, Node.js, Python 또는 C++을 사용하여 기본 스크립트 작업을 만들 수 있습니다.

콘솔

Google Cloud 콘솔을 사용하여 기본 스크립트 작업을 만들려면 다음을 수행합니다.

  1. Google Cloud 콘솔에서 작업 목록 페이지로 이동합니다.

    작업 목록으로 이동

  2. 만들기를 클릭합니다. 일괄 작업 만들기 페이지가 열립니다. 왼쪽 창에서 작업 세부정보 페이지가 선택됩니다.

  3. 작업 세부정보 페이지를 구성합니다.

    1. 선택 사항: 작업 이름 필드에서 작업 이름을 맞춤설정합니다.

      예를 들어 example-basic-job를 입력합니다.

    2. 태스크 세부정보 섹션을 구성합니다.

      1. 새 실행 가능 항목 창에서 이 작업을 실행할 스크립트 또는 컨테이너를 하나 이상 추가합니다.

        예를 들어 스크립트 하나를 추가하려면 다음을 수행합니다.

        1. 스크립트를 선택합니다. 텍스트 상자가 나타납니다.

        2. 텍스트 상자에 이 작업의 각 태스크에 대해 실행할 스크립트를 입력합니다.

          예를 들어 다음 스크립트를 입력합니다.

          echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.
          
        3. 완료를 클릭합니다.

      2. 태스크 수 필드에 이 작업의 태스크 수를 입력합니다. 이 값은 1태스크 그룹당 태스크 한도 사이의 정수여야 합니다.

        예를 들어 4를 입력합니다.

      3. 동시 실행 필드에 동시에 실행할 작업 수를 입력합니다. 이 수는 총 태스크 수보다 클 수 없으며 1작업당 동시 태스크 한도 사이의 정수여야 합니다.

        예를 들어 2를 입력합니다.

  4. 리소스 사양 페이지를 구성합니다.

    1. 왼쪽 창에서 리소스 사양을 클릭합니다. 리소스 사양 페이지가 열립니다.

    2. VM 프로비저닝 모델 섹션에서 이 작업의 VM에 대한 프로비저닝 모델에 대해 다음 옵션 중 하나를 선택합니다.

      • 작업이 선점을 감내할 수 있고 할인된 가격으로 VM을 사용하려면 Spot을 선택합니다.

      • 그렇지 않으면 표준을 선택합니다.

      예를 들어 표준(기본값)을 선택합니다.

    3. 이 작업의 위치를 선택합니다.

      1. 리전 필드에서 리전을 선택합니다.

        예를 들어 us-central1 (Iowa)(기본값)을 선택합니다.

      2. 영역 필드에서 다음 중 하나를 수행합니다.

        • 이 작업이 특정 영역에서만 실행되도록 제한하려면 영역을 선택합니다.

        • 그렇지 않으면 모두를 선택합니다.

        예를 들어 모두(기본값)를 선택합니다.

    4. 다음 머신 계열 중 하나를 선택합니다.

      • 일반적인 워크로드의 경우 범용을 클릭합니다.

      • 성능 집약적인 워크로드의 경우 컴퓨팅 최적화를 클릭합니다.

      • 메모리 집약적인 워크로드의 경우 메모리 최적화를 클릭합니다.

      예를 들어 범용(기본값)을 클릭합니다.

    5. 계열 필드에서 이 작업의 VM에 대한 머신 계열을 선택합니다.

      예를 들어 머신 계열에 범용을 선택한 경우 E2(기본값)를 선택합니다.

    6. 머신 유형 필드에서 이 작업의 VM에 대한 머신 유형을 선택합니다.

      예를 들어 머신 계열에서 E2를 선택한 경우 e2-medium(vCPU 2개, 메모리 4GB)(기본값)을 선택합니다.

    7. 각 태스크에 필요한 VM 리소스 양을 구성합니다.

      1. 코어 필드에 태스크당 vCPU 양을 입력합니다.

        예를 들어 1(기본값)을 입력합니다.

      2. 메모리 필드에 태스크당 RAM의 크기를 GB 단위로 입력합니다.

        예를 들어 0.5(기본값)을 입력합니다.

  5. 선택사항: 작업 구성을 검토하려면 왼쪽 창에서 미리보기를 클릭합니다.

  6. 만들기를 클릭합니다.

작업 세부정보 페이지에 자신이 만든 작업이 표시됩니다.

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: (선택사항) 각 태스크에 할당할 milliCPU 단위의 코어(특히 물리적 코어의 절반을 나타내는 vCPU)의 수입니다. cpuMilli 필드가 지정되지 않은 경우 값은 2000(vCPU 2개)으로 설정됩니다.
    • MEMORY: 선택사항. 각 태스크에 할당할 메모리 양(MB). memoryMib 필드가 지정되지 않은 경우 값은 2000(2GB)으로 설정됩니다.
    • MAX_RETRY_COUNT: 선택사항. 태스크의 최대 재시도 횟수입니다. 값은 0에서 10 사이의 정수여야 합니다. maxRetryCount 필드가 지정되지 않은 경우 값은 0으로 설정됩니다. 즉, 태스크를 다시 시도하지 않습니다. maxRetryCount 필드에 대한 자세한 내용은 태스크 재시도 자동화를 참조하세요.
    • MAX_RUN_DURATION: 선택사항. 재시도 또는 실패 전에 태스크가 실행될 수 있는 최대 시간은 뒤에 s가 있는 초 단위의 값으로 형식이 지정됩니다(예: 1시간의 경우 3600s). maxRunDuration 필드를 지정하지 않으면 값이 작업의 최대 실행 시간으로 설정됩니다. maxRunDuration 필드에 대한 자세한 내용은 제한 시간을 사용하여 태스크 및 실행 가능 항목의 실행 시간 제한을 참조하세요.
    • TASK_COUNT: 선택사항. 작업의 태스크 수. 이 값은 1태스크 그룹당 태스크 한도 사이의 정수여야 합니다. taskCount 필드를 지정하지 않으면 값이 1로 설정됩니다.
    • PARALLELISM: (선택사항) 작업이 동시에 실행하는 태스크 수입니다. 이 수는 태스크 수보다 클 수 없으며 1작업당 동시 태스크 한도 사이의 정수여야 합니다. 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: (선택사항) 각 태스크에 할당할 milliCPU 단위의 코어(특히 물리적 코어의 절반을 나타내는 vCPU)의 수입니다. cpuMilli 필드가 지정되지 않은 경우 값은 2000(vCPU 2개)으로 설정됩니다.
  • MEMORY: 선택사항. 각 태스크에 할당할 메모리 양(MB). memoryMib 필드가 지정되지 않은 경우 값은 2000(2GB)으로 설정됩니다.
  • MAX_RETRY_COUNT: 선택사항. 태스크의 최대 재시도 횟수입니다. 값은 0에서 10 사이의 정수여야 합니다. maxRetryCount 필드가 지정되지 않은 경우 값은 0으로 설정됩니다. 즉, 태스크를 다시 시도하지 않습니다. maxRetryCount 필드에 대한 자세한 내용은 태스크 재시도 자동화를 참조하세요.
  • MAX_RUN_DURATION: 선택사항. 재시도 또는 실패 전에 태스크가 실행될 수 있는 최대 시간은 뒤에 s가 있는 초 단위의 값으로 형식이 지정됩니다(예: 1시간의 경우 3600s). maxRunDuration 필드를 지정하지 않으면 값이 작업의 최대 실행 시간으로 설정됩니다. maxRunDuration 필드에 대한 자세한 내용은 제한 시간을 사용하여 태스크 및 실행 가능 항목의 실행 시간 제한을 참조하세요.
  • TASK_COUNT: 선택사항. 작업의 태스크 수. 이 값은 1태스크 그룹당 태스크 한도 사이의 정수여야 합니다. taskCount 필드를 지정하지 않으면 값이 1로 설정됩니다.
  • PARALLELISM: (선택사항) 작업이 동시에 실행하는 태스크 수. 이 수는 태스크 수보다 클 수 없으며 1작업당 동시 태스크 한도 사이의 정수여야 합니다. 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)

C++

C++

자세한 내용은 Batch C++ API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

#include "google/cloud/batch/v1/batch_client.h"

  [](std::string const& project_id, std::string const& location_id,
     std::string const& job_id) {
    // Initialize the request; start with the fields that depend on the sample
    // input.
    google::cloud::batch::v1::CreateJobRequest request;
    request.set_parent("projects/" + project_id + "/locations/" + location_id);
    request.set_job_id(job_id);
    // Most of the job description is fixed in this example; use a string to
    // initialize it.
    auto constexpr kText = R"pb(
      task_groups {
        task_count: 4
        task_spec {
          compute_resource { cpu_milli: 500 memory_mib: 16 }
          max_retry_count: 2
          max_run_duration { seconds: 3600 }
          runnables {
            script {
              text: "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
            }
          }
        }
      }
      allocation_policy {
        instances {
          policy { machine_type: "e2-standard-4" provisioning_model: STANDARD }
        }
      }
      labels { key: "env" value: "testing" }
      labels { key: "type" value: "script" }
      logs_policy { destination: CLOUD_LOGGING }
    )pb";
    auto* job = request.mutable_job();
    if (!google::protobuf::TextFormat::ParseFromString(kText, job)) {
      throw std::runtime_error("Error parsing Job description");
    }
    // Create a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    auto response = client.CreateJob(request);
    if (!response) throw std::move(response).status();
    std::cout << "Job : " << response->DebugString() << "\n";
  }

환경 변수 사용

작업으로 실행할 컨테이너 이미지 또는 스크립트를 작성할 때 환경 변수를 사용합니다. 모든 일괄 작업에 대해 사전 정의된 환경 변수와 작업을 만들 때 정의하는 커스텀 환경 변수를 사용할 수 있습니다.

사전 정의된 환경 변수 사용

기본적으로 작업의 실행 가능한 항목은 사전 정의된 다음 환경 변수를 사용할 수 있습니다.

  • BATCH_TASK_COUNT: 이 태스크 그룹의 총 태스크 수입니다.
  • BATCH_TASK_INDEX: 태스크 그룹에 있는 이 태스크의 색인 번호입니다. 첫 번째 태스크의 색인은 0이며 태스크가 추가될 때마다 증가합니다.
  • BATCH_HOSTS_FILE: 이 태스크 그룹에서 실행 중인 모든 VM 인스턴스가 나열된 파일의 경로입니다. 이 환경 변수를 사용하려면 requireHostsFile 필드true로 설정해야 합니다.
  • BATCH_TASK_RETRY_ATTEMPT: 이 태스크가 이미 시도된 횟수입니다. 이 값은 태스크 첫 시도 시 0이며 재시도할 때마다 증가합니다. 태스크에 허용되는 총 재시도 횟수는 maxRetryCount 필드 값(정의되지 않은 경우 0)에 따라 결정됩니다. 재시도에 대한 자세한 내용은 태스크 재시도 자동화를 참조하세요.

사전 정의된 환경 변수를 사용하는 방법의 예시는 이 문서에서 기본 작업 만들기에 있는 이전 실행 가능 항목 예시를 참조하세요.

커스텀 환경 변수 정의 및 사용

원하는 경우 작업에서 커스텀 환경 변수 하나 이상을 정의할 수 있습니다.

원하는 데이터 범위를 기준으로 특정 환경에서 각 변수를 정의합니다.

선택한 환경에서 다음 환경 하위 필드 중 하나를 사용하여 각 변수의 이름과 값을 정의합니다.

gcloud CLI 또는 Batch API를 사용하여 작업의 커스텀 환경 변수를 정의하고 사용할 수 있습니다. 다음 예시에서는 표준 변수를 정의하고 사용하는 작업 두 개를 만드는 방법을 설명합니다. 첫 번째 예시 작업에는 특정 실행 가능 항목의 변수가 있습니다. 두 번째 예시 작업에는 태스크마다 값이 다른 배열 변수가 있습니다.

gcloud

각 태스크가 실행하는 실행 가능한 항목에 환경 변수를 전달하는 작업을 정의하려면 실행 가능한 항목에 환경 변수 정의 및 사용 방법에 대한 예시를 참조하세요. 그렇지 않고 태스크 색인에 따라 환경 변수 목록을 다른 작업에 전달하는 작업을 정의하려면 각 태스크의 환경 변수 정의 및 사용 방법에 대한 예시를 참조하세요.

실행 가능한 항목을 위한 환경 변수 정의 및 사용

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_INDEX0과 동일합니다.
    • TASK_VARIABLE_VALUE_1: 두 번째 태스크에 전달된 환경 변수의 값이며 BATCH_TASK_INDEX1과 동일합니다.
    • TASK_VARIABLE_VALUE_2: 세 번째 태스크에 전달된 환경 변수의 값이며 BATCH_TASK_INDEX2와 동일합니다.
  2. 다음 명령어를 실행합니다.

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

API

각 태스크가 실행하는 실행 가능한 항목에 환경 변수를 전달하는 작업을 정의하려면 실행 가능한 항목에 환경 변수 정의 및 사용 방법에 대한 예시를 참조하세요. 그렇지 않고 태스크 색인에 따라 환경 변수 목록을 다른 작업에 전달하는 작업을 정의하려면 각 태스크의 환경 변수 정의 및 사용 방법에 대한 예시를 참조하세요.

실행 가능한 항목을 위한 환경 변수 정의 및 사용

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_INDEX0과 동일합니다.
  • TASK_VARIABLE_VALUE_1: 두 번째 태스크에 전달된 환경 변수의 값이며 BATCH_TASK_INDEX1과 동일합니다.
  • TASK_VARIABLE_VALUE_2: 세 번째 태스크에 전달된 환경 변수의 값이며 BATCH_TASK_INDEX2와 동일합니다.

다음 단계