Neste documento, explicamos como definir os recursos de VM para um job em lote. especificando um Modelo de instância de VM do Compute Engine ao criar o job.
Os tipos de recursos da VM em que um job é executado
(instances[]
subcampos) são automaticamente
definidos pelo Batch, a menos que você os defina usando
um dos seguintes métodos:
- Use o campo
policy
. para definir diretamente os recursos de VM de um job, como exemplificado Crie um job básico. - Use o campo
instanceTemplate
. para definir os recursos da VM de um job especificando um modelo de instância da VM, como explicado neste documento. Este método é obrigatório para criar um job que use imagens de VM não padrão.
Antes de começar
- Se você nunca usou o Batch antes, revise Introdução ao Batch e ativar o Batch. pré-requisitos para projetos e usuários.
-
Para ter as permissões necessárias para criar um job, peça ao administrador para conceder a você os seguintes papéis do IAM:
-
Editor de jobs em lote (
roles/batch.jobsEditor
) no projeto -
Usuário da conta de serviço (
roles/iam.serviceAccountUser
) na conta de serviço do job, que é a conta de serviço padrão do Compute Engine -
Crie um job a partir de um modelo de instância de VM do Compute Engine:
Leitor do Compute (
roles/compute.viewer
) no modelo de instância de VM
Para mais informações sobre como conceder papéis, consulte Gerenciar acesso.
Também é possível conseguir as permissões necessárias com papéis personalizados ou outros papéis predefinidos.
-
Editor de jobs em lote (
Criar um job usando um modelo de instância de VM do Compute Engine
Esta seção fornece exemplos de como criar um job de script básico a partir um modelo de instância de VM atual. É possível criar um job a partir de um modelo de instância de VM usando a CLI gcloud, a API Batch, Go, Java, Node.js, Python ou C++.
gcloud
Para criar um job a partir de um modelo de instância de VM usando o
CLI gcloud, use o comando gcloud batch jobs submit
.
e especificar o modelo de instância de VM no arquivo de configuração JSON do job.
Por exemplo, para criar um job de script básico usando um modelo de instância de VM:
Crie um arquivo JSON chamado
hello-world-instance-template.json
com o conteúdo a seguir:{ "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": [ { "installGpuDrivers": INSTALL_GPU_DRIVERS, "instanceTemplate": "INSTANCE_TEMPLATE_NAME" } ] }, "labels": { "department": "finance", "env": "testing" }, "logsPolicy": { "destination": "CLOUD_LOGGING" } }
Substitua:
INSTALL_GPU_DRIVERS
: opcional. Quando definido comotrue
, o Batch busca os drivers necessários para Tipo de GPU especificado na instância de VM do Compute Engine modelo, e o Batch os instala em seu nome. Para mais informações, veja como criar um job que use uma GPU.INSTANCE_TEMPLATE_NAME
: o nome de um objeto existente. modelo de instância de VM do Compute Engine. Saiba como criar e listar modelos de instância.
Execute este comando:
gcloud batch jobs submit example-template-job \ --location us-central1 \ --config hello-world-instance-template.json
API
Para criar um job básico usando a API Batch, use o
Método jobs.create
e especificar um modelo de instância de VM no campo allocationPolicy
.
Por exemplo, para criar jobs de script básicos usando um modelo de instância de VM, use a seguinte solicitação:
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": [
{
"installGpuDrivers": INSTALL_GPU_DRIVERS,
"instanceTemplate": "INSTANCE_TEMPLATE_NAME"
}
]
},
"labels": {
"department": "finance",
"env": "testing"
},
"logsPolicy": {
"destination": "CLOUD_LOGGING"
}
}
Substitua:
PROJECT_ID
: o ID do projeto do seu projeto.INSTALL_GPU_DRIVERS
: opcional. Quando definido comotrue
: o Batch busca os drivers necessários para a GPU especificado no modelo de instância de VM do Compute Engine. e o Batch os instala em seu nome. Para mais informações, veja como criar um job que usa uma GPU.INSTANCE_TEMPLATE_NAME
: o nome de um modelo atual de instância de VM do Compute Engine. Saiba como criar e listar modelos de instância.
Go
Go
Para mais informações, consulte a API Batch Go documentação de referência.
Para autenticar no Batch, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
Java
Java
Para mais informações, consulte a API Batch Java documentação de referência.
Para autenticar no Batch, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
Node.js
Node.js
Para mais informações, consulte a API Batch Node.js documentação de referência.
Para autenticar no Batch, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
Python
Python
Para mais informações, consulte a API Batch Python documentação de referência.
Para autenticar no Batch, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
C++
C++
Para mais informações, consulte a API Batch C++ documentação de referência.
Para autenticar no Batch, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
A seguir
- Se você tiver problemas para criar ou executar um job, consulte Solução de problemas.
- Ver tarefas e tarefas.
- Saiba mais sobre opções de criação de jobs.