En este documento, se explica cómo usar etiquetas para organizar tus recursos de Batch.
Las etiquetas son pares clave-valor que se aplican a los recursos para agruparlos y describirlos. Batch tiene etiquetas predefinidas, que se que se aplican a los recursos, y las etiquetas personalizadas, que puedes definir y aplicar cuando en la creación de un trabajo.
Las etiquetas te permiten filtrar los resultados de las listas de recursos y los informes de Facturación de Cloud. Por ejemplo, puedes usar etiquetas para lo siguiente:
Aclara y organiza la lista de trabajos de tu proyecto.
Distinguir los ejecutables de un trabajo usando etiquetas para describir el tipo de contenedor o la secuencia de comandos que especifique.
Analiza los costos filtrando los informes de Facturación de Cloud para los recursos creados por lotes o trabajos específicos.
Para obtener más información sobre las etiquetas, consulta la documentación de Compute Engine sobre las etiquetas.
Antes de comenzar
- Si nunca usaste Batch, revisa Comienza a usar Batch y habilitar Batch completando el requisitos previos para los proyectos y usuarios.
-
Para obtener los permisos que necesitas para crear un trabajo, pídele a tu administrador que te otorgue los siguientes roles de IAM:
-
Editor de trabajos por lotes (
roles/batch.jobsEditor
) en el proyecto -
Usuario de cuenta de servicio (
roles/iam.serviceAccountUser
) en la cuenta de servicio del trabajo, que, de forma predeterminada, es la cuenta de servicio predeterminada de Compute Engine
Para obtener más información sobre cómo otorgar roles, consulta Administra el acceso a proyectos, carpetas y organizaciones.
También puedes obtener los permisos necesarios mediante roles personalizados o cualquier otro rol predefinido.
-
Editor de trabajos por lotes (
Restricciones
Además del artículo requisitos para las etiquetas especificadas en la documentación de Compute Engine, El trabajo por lotes y sus recursos tienen las siguientes restricciones:
Por lotes, solo se admiten etiquetas para los recursos que se crean con este comando y de los siguientes tipos:
Trabajos
Ejecutables
Unidades de procesamiento gráfico (GPU) para un trabajo (si corresponde)
Discos persistentes (discos de arranque y cualquier volúmenes de almacenamiento) de un trabajo
Instancias de máquina virtual (VM) para un trabajo
Luego de considerar las etiquetas predefinidas que Batch se aplica automáticamente a un trabajo, puedes definir la las siguientes cantidades de etiquetas personalizadas:
Puedes definir un máximo de 63 etiquetas personalizadas para aplicar al trabajo y a su ejecutables.
Puedes definir un máximo de 61 etiquetas personalizadas para aplicarlas a cada GPU, disco persistente y VM creada para la tarea.
Los lotes solo admiten la definición de etiquetas personalizadas con nombres únicos. Esto tiene las siguientes consecuencias:
Si intentas anular una etiqueta predefinida, se generarán errores.
La definición de una etiqueta personalizada duplicada anula la etiqueta personalizada existente.
Batch solo admite la definición de etiquetas cuando se crea un trabajo.
No se pueden agregar, actualizar ni quitar etiquetas de trabajos y ejecutables.
Aunque es posible usar Compute Engine para agregar, actualizar o remover etiquetas de los discos persistentes y las VMs creadas para trabajos, no se recomienda. No se puede estimar de forma confiable el período en el que existen los recursos de un trabajo, y es posible que los cambios no funcionen correctamente con Batch.
Si deseas usar etiquetas para filtrar tu lista de trabajos, debes hacer lo siguiente: ver tu lista de trabajos con gcloud CLI o la API de Batch.
Etiquetas predefinidas
Cada etiqueta predefinida tiene una clave que comienza con el prefijo batch-
. De
Batch aplica automáticamente los siguientes parámetros predefinidos
etiquetas:
Sigue estos pasos en cada trabajo que crees:
batch-job-id
: El valor de esta etiqueta se establece en el nombre del trabajo.
A cada GPU, disco persistente y VM creada para un trabajo, haz lo siguiente:
batch-job-id
: El valor de esta etiqueta se establece en el nombre del trabajo.batch-job-uid
: El valor de esta etiqueta se establece en el nombre único del trabajo. identificador (UID).batch-node
: El valor de esta etiqueta es nulo, solo agrupa todos las GPU, los discos persistentes y las VMs que se crean para los trabajos. Por ejemplo, usa esta etiqueta cuando visualices un informe de Facturación de Cloud para identificar los costos de todas las GPUs, los discos persistentes y las VMs que creó Batch.
Define etiquetas personalizadas
De manera opcional, puedes definir una o más etiquetas personalizadas cuando creas un trabajo. Puedes definir etiquetas personalizadas con claves nuevas o claves que ya usa tu proyecto. Para definir etiquetas personalizadas, selecciona uno o más de los siguientes métodos en este documento según el propósito de la etiqueta:
Define etiquetas personalizadas para el trabajo y sus recursos.
En esta sección, se explica cómo aplicar una o más etiquetas personalizadas a la tarea y a cada GPU, disco persistente y VM creada para la tarea. Después de crear el trabajo, puedes usar estas etiquetas para filtrar los informes de Facturación de Cloud y las listas de trabajos, discos persistentes y VMs de tu proyecto.
Define etiquetas personalizadas para el trabajo.
En esta sección, se explica cómo aplicar una o más etiquetas personalizadas al trabajo. Después del cuando creas el trabajo, puedes usar estas etiquetas para filtrar las listas de de seguridad en la nube.
Define etiquetas personalizadas para elementos ejecutables.
En esta sección, se explica cómo aplicar una o más etiquetas personalizadas a una o más de ellas. ejecutables para el trabajo. Después de crear el trabajo, puedes usar estas etiquetas para lo siguiente: filtrar las listas de trabajos de tu proyecto.
Define etiquetas personalizadas para la tarea y sus recursos
Las etiquetas definidas en el
Campo labels
para la política de asignación de un trabajo
al trabajo, así como a cada GPU (si corresponde), disco persistente (todos
discos de arranque y cualquier volumen de almacenamiento nuevo) y una VM creada para el trabajo.
Puedes definir etiquetas para un trabajo y sus recursos cuando lo creas con la CLI de gcloud o la API de Batch.
gcloud
Por ejemplo, para crear un trabajo de contenedor básico en us-central1
que defina dos
las etiquetas personalizadas
que se aplican al trabajo y los recursos
sigue estos pasos:
Crear un archivo JSON que especifique los detalles de configuración del trabajo y la Campo
allocationPolicy.labels
.{ "allocationPolicy": { "instances": [ { "policy": { "machineType": "e2-standard-4" } } ], "labels": { "VM_LABEL_NAME1": "VM_LABEL_VALUE1", "VM_LABEL_NAME2": "VM_LABEL_VALUE2" } }, "taskGroups": [ { "taskSpec": { "runnables": [ { "container": { "imageUri": "gcr.io/google-containers/busybox", "entrypoint": "/bin/sh", "commands": [ "-c", "echo Hello world!" ] } } ] } } ] }
Reemplaza lo siguiente:
VM_LABEL_NAME1
: Es el nombre de la primera etiqueta que se aplicará. a las VMs creadas para el trabajo.VM_LABEL_VALUE1
: Es el valor de la primera etiqueta que se aplicará a las VMs creadas para la tarea.VM_LABEL_NAME2
: Es el nombre de la segunda etiqueta que se aplicará a las VMs creadas para la tarea.VM_LABEL_VALUE2
: Es el valor de la segunda etiqueta que se enviará. se aplican a las VMs creadas para el trabajo.
Crea el trabajo en
us-central1
con el comando Comandogcloud batch jobs submit
:gcloud batch jobs submit example-job \ --config=JSON_CONFIGURATION_FILE \ --location=us-central1
Reemplaza
JSON_CONFIGURATION_FILE
por la ruta de acceso al archivo JSON con los detalles de configuración del trabajo que creaste en el paso anterior.
API
Por ejemplo, para crear un trabajo de contenedor básico en us-central1
que defina dos etiquetas personalizadas que se apliquen al trabajo y a los recursos creados para él, realiza una solicitud POST
al método jobs.create
y especifica el campo allocationPolicy.labels
.
POST https://batch.googleapis.com/v1/projects/example-project/locations/us-central1/jobs?job_id=example-job
{
"allocationPolicy": {
"instances": [
{
"policy": {
"machineType": "e2-standard-4"
}
}
],
"labels": {
"VM_LABEL_NAME1": "VM_LABEL_VALUE1",
"VM_LABEL_NAME2": "VM_LABEL_VALUE2"
}
},
"taskGroups": [
{
"taskSpec": {
"runnables": [
{
"container": {
"imageUri": "gcr.io/google-containers/busybox",
"entrypoint": "/bin/sh",
"commands": [
"-c",
"echo Hello world!"
]
}
}
]
}
}
]
}
Reemplaza lo siguiente:
VM_LABEL_NAME1
: Es el nombre de la primera etiqueta a la que se aplicará. las VMs creadas para el trabajo.VM_LABEL_VALUE1
: Es el valor de la primera etiqueta que se aplicará a las VMs creadas para la tarea.VM_LABEL_NAME2
: Es el nombre de la segunda etiqueta que se aplicará a las VMs creadas para la tarea.VM_LABEL_VALUE2
: Es el valor de la segunda etiqueta que se aplicará. a las VMs creadas para el trabajo.
Java
Node.js
Python
Definir etiquetas personalizadas para el trabajo
Etiquetas definidas en el campo labels
del trabajo.
solo se aplican al trabajo.
Puedes definir etiquetas para un trabajo cuando lo creas con el gcloud CLI o la API de Batch.
gcloud
Por ejemplo, para crear un trabajo de contenedor básico en us-central1
que defina
dos etiquetas personalizadas que se apliquen al trabajo en sí, sigue estos pasos:
Crea un archivo JSON que especifique los detalles de configuración de la tarea y el campo
labels
.{ "taskGroups": [ { "taskSpec": { "runnables": [ { "container": { "imageUri": "gcr.io/google-containers/busybox", "entrypoint": "/bin/sh", "commands": [ "-c", "echo Hello World!" ] } } ] } } ], "labels": { "JOB_LABEL_NAME1": "JOB_LABEL_VALUE1", "JOB_LABEL_NAME2": "JOB_LABEL_VALUE2" } }
Reemplaza lo siguiente:
JOB_LABEL_NAME1
: Es el nombre de la primera etiqueta que se usará. se postulan a tu trabajo.JOB_LABEL_VALUE1
: Es el valor de la primera etiqueta que se aplicará a tu trabajo.JOB_LABEL_NAME2
: Es el nombre de la segunda etiqueta que se aplicará a tu trabajo.JOB_LABEL_VALUE2
: El valor de la segunda etiqueta que se enviará se postulan a tu trabajo.
Crea el trabajo en
us-central1
con el comandogcloud batch jobs submit
y las siguientes marcas:gcloud batch jobs submit example-job \ --config=JSON_CONFIGURATION_FILE \ --location=us-central1
Reemplaza
JSON_CONFIGURATION_FILE
por la ruta de acceso a Archivo JSON con los detalles de configuración del trabajo que creaste anteriormente paso.
API
Por ejemplo, para crear un trabajo de contenedor en us-central1
que defina dos
etiquetas personalizadas para aplicar a los trabajos en sí, realiza una solicitud POST
al
Método jobs.create
y especifica el
Campo labels
.
POST https://batch.googleapis.com/v1/projects/example-project/locations/us-central1/jobs?job_id=example-job
{
"taskGroups": [
{
"taskSpec": {
"runnables": [
{
"container": {
"imageUri": "gcr.io/google-containers/busybox",
"entrypoint": "/bin/sh",
"commands": [
"-c",
"echo Hello World!"
]
}
}
]
}
}
],
"labels": {
"JOB_LABEL_NAME1": "JOB_LABEL_VALUE1",
"JOB_LABEL_NAME2": "JOB_LABEL_VALUE2"
}
}
Reemplaza lo siguiente:
JOB_LABEL_NAME1
: Es el nombre de la primera etiqueta a la que se aplicará. en tu trabajo.JOB_LABEL_VALUE1
: Es el valor de la primera etiqueta que se aplicará. a tu trabajo.JOB_LABEL_NAME2
: Es el nombre de la segunda etiqueta que se aplicará a tu trabajo.JOB_LABEL_VALUE2
: Es el valor de la segunda etiqueta que se aplicará. a tu trabajo.
Java
Node.js
Python
Define etiquetas personalizadas para elementos ejecutables
Las etiquetas definidas en el
Campo labels
para un ejecutable
solo se aplican a ese ejecutable.
Puedes definir etiquetas para uno o más elementos ejecutables cuando creas un trabajo con la CLI de gcloud o la API de Batch.
gcloud
Por ejemplo, para crear un trabajo en us-central1
que defina dos etiquetas personalizadas, una etiqueta personalizada para cada uno de los ejecutables del trabajo, sigue estos pasos:
Crea un archivo JSON que especifique los detalles de configuración de la tarea y los campos
runnables.labels
.{ "taskGroups": [ { "taskSpec": { "runnables": [ { "container": { "imageUri": "gcr.io/google-containers/busybox", "entrypoint": "/bin/sh", "commands": [ "-c", "echo Hello from task ${BATCH_TASK_INDEX}!" ] }, "labels": { "RUNNABLE1_LABEL_NAME1": "RUNNABLE1_LABEL_VALUE1" } }, { "script": { "text": "echo Hello from task ${BATCH_TASK_INDEX}!" }, "labels": { "RUNNABLE2_LABEL_NAME1": "RUNNABLE2_LABEL_VALUE1" } } ] } } ] }
Reemplaza lo siguiente:
RUNNABLE1_LABEL_NAME1
: Es el nombre de la etiqueta que se aplicará al primer elemento ejecutable del trabajo.RUNNABLE1_LABEL_VALUE1
: Es el valor de la etiqueta que se usará. se aplican al primer ejecutable del trabajo.RUNNABLE2_LABEL_NAME1
: Es el nombre de la etiqueta que se aplicará. al segundo ejecutable del trabajo.RUNNABLE2_LABEL_VALUE1
: Es el valor de la etiqueta que se aplicará al segundo elemento ejecutable de la tarea.
Crea el trabajo en
us-central1
con el comando Comandogcloud batch jobs submit
:gcloud batch jobs submit example-job \ --config=JSON_CONFIGURATION_FILE \ --location=us-central1
Reemplaza
JSON_CONFIGURATION_FILE
por la ruta de acceso a Archivo JSON con los detalles de configuración del trabajo que creaste anteriormente paso.
API
Por ejemplo, para crear un trabajo en us-central1
que defina dos etiquetas personalizadas, una para cada uno de los ejecutables del trabajo, realiza una solicitud POST
al método jobs.create
y especifica los campos runnables.labels
.
POST https://batch.googleapis.com/v1/projects/example-project/locations/us-central1/jobs?job_id=example-job
{
"taskGroups": [
{
"taskSpec": {
"runnables": [
{
"container": {
"imageUri": "gcr.io/google-containers/busybox",
"entrypoint": "/bin/sh",
"commands": [
"-c",
"echo Hello from ${BATCH_TASK_INDEX}!"
]
},
"labels": {
"RUNNABLE1_LABEL_NAME1": "RUNNABLE1_LABEL_VALUE1"
}
},
{
"script": {
"text": "echo Hello from ${BATCH_TASK_INDEX}!"
},
"labels": {
"RUNNABLE2_LABEL_NAME1": "RUNNABLE2_LABEL_VALUE1"
}
}
]
}
}
]
}
Reemplaza lo siguiente:
RUNNABLE1_LABEL_NAME1
: Es el nombre de la etiqueta a la que se aplicará. el primer trabajo es ejecutable.RUNNABLE1_LABEL_VALUE1
: Es el valor de la etiqueta que se aplicará al ejecutable del primer trabajo.RUNNABLE2_LABEL_NAME1
: Es el nombre de la etiqueta a la que se aplicará. el segundo trabajo es ejecutable.RUNNABLE2_LABEL_VALUE1
: Es el valor de la etiqueta que se aplicará. al ejecutable del segundo trabajo.
Java
Node.js
Python
¿Qué sigue?
Usa etiquetas como filtros cuando realices las siguientes acciones:
Obtén más información para borrar trabajos.