Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Os rótulos do Cloud Run são pares de chave-valor aplicados ao
serviço e às revisões do Cloud Run. Nesta página, mostramos como definir, modificar e excluir rótulos no serviço e nas revisões do Cloud Run.
Quando você define um rótulo em um serviço do Cloud Run, uma nova revisão com esse rótulo é criada para esse serviço. O rótulo não é aplicado a revisões mais antigas.
Os possíveis usos incluem:
Alocação de custos e detalhamentos de faturamento.
Identificar recursos usados por equipes ou centros de custo individuais.
Diferenciar ambientes de implantação (produção, preparo, controle de qualidade ou teste).
Identificar os proprietários e os rótulos de estado
Filtrar registros no Logging.
Regras de uso de rótulos
A regra a seguir se aplica ao uso de rótulos definidos em um
serviço do Cloud Run:
Para receber as permissões necessárias para configurar e implantar os serviços do Cloud Run,
peça ao administrador para conceder a você os
seguintes papéis do IAM:
Se você estiver implantando um serviço
ou uma função do código-fonte, também
precisará ter outros papéis concedidos a você no projeto e na
conta de serviço do Cloud Build.
Qualquer mudança na configuração leva à criação de uma nova revisão. As próximas revisões também recebem automaticamente essa configuração, a menos que você faça atualizações explícitas para alterá-la.
Os rótulos definidos anteriormente para as funções do Cloud Run usando comandos gcloud functions ou a API Cloud Functions v2 são propagados para o Cloud Run quando você implanta as funções no Cloud Run.
É possível definir ou modificar rótulos usando o console Google Cloud , a linha de comando gcloud
ou um arquivo YAML ao
implantar uma nova revisão.
Para atualizar mais de um rótulo, forneça uma lista delimitada por vírgulas de pares de
chave-valor. O comando update-labels define um novo valor para a chave
de rótulo, se ele já existir. Caso contrário, ele criará um novo rótulo.
Para criar mais de um rótulo durante a implantação, forneça uma lista de pares chave-valor delimitada
por vírgulas.
YAML
Se você estiver criando um novo serviço, pule esta etapa.
Se você estiver atualizando um serviço existente, faça o download da configuração YAML correspondente:
REVISION por um novo nome de revisão ou excluí-lo (se houver). Se você fornecer um novo nome de revisão, ele precisará atender aos seguintes critérios:
Começa com SERVICE-
Contém apenas letras minúsculas, números e -
Não termina com um -
Não excede 63 caracteres
metadata.labels define os identificadores no objeto de serviço, enquanto
spec.template.metadata.label define os identificadores na revisão criada.
Somente os identificadores definidos na revisão são passados para os registros e o faturamento.
Crie ou atualize o serviço usando o seguinte comando:
resource"google_cloud_run_v2_service""default"{name="cloudrun-service-labels"location="us-central1"deletion_protection=false # set to "true" in productiontemplate{containers{image="us-docker.pkg.dev/cloudrun/container/hello"} # Labelslabels={foo:"bar"baz:"quux"}}}
O snippet anterior adiciona dois rótulos, foo (com valor bar) e baz (com valor quux), à instância do Cloud Run.
Adicionar os rótulos em template define os rótulos da revisão: apenas os rótulos definidos para a revisão são transmitidos para os registros e o faturamento. Se você adicionar os
rótulos a um local diferente de template, o rótulo será definido para o
serviço, e não para a revisão.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-04 UTC."],[],[],null,["Cloud Run labels are key-value pairs that are applied to\nCloud Run service and revisions. This page shows how to set, modify, and\ndelete labels on your Cloud Run service and revisions.\nNote that when you set a label on a Cloud Run\nservice, a new revision with this label is created for this\nservice; the label is not applied to older revisions.\n\nPossible uses include:\n\n- Cost allocation and billing breakdowns.\n- Identify resources used by individual teams or cost centers.\n- Distinguish deployment environments (prod, staging, qa, or test).\n- Identify owners and state labels.\n- Filter logs in Logging.\n\nLabels usage rules\n\nThe following rule applies to the use of labels set on a\nCloud Run service:\n\nOnly [valid Google Cloud labels](/resource-manager/docs/creating-managing-labels) can be used on Cloud Run.\n\nRequired roles\n\n\nTo get the permissions that\nyou need to configure and deploy Cloud Run services,\n\nask your administrator to grant you the\nfollowing IAM roles:\n\n- [Cloud Run Developer](/iam/docs/roles-permissions/run#run.developer) (`roles/run.developer`) on the Cloud Run service\n- [Service Account User](/iam/docs/roles-permissions/iam#iam.serviceAccountUser) (`roles/iam.serviceAccountUser`) on the service identity\n\n\nIf you are deploying a [service](/run/docs/deploying-source-code#required_roles)\nor [function](/run/docs/deploy-functions#required-roles) from source code, you\nmust also have additional roles granted to you on your project and\nCloud Build service account.\n\nFor a list of IAM roles and permissions that are associated with\nCloud Run, see\n[Cloud Run IAM roles](/run/docs/reference/iam/roles)\nand [Cloud Run IAM permissions](/run/docs/reference/iam/permissions).\nIf your Cloud Run service interfaces with\nGoogle Cloud APIs, such as Cloud Client Libraries, see the\n[service identity configuration guide](/run/docs/configuring/services/service-identity).\nFor more information about granting roles, see\n[deployment permissions](/run/docs/reference/iam/roles#additional-configuration)\nand [manage access](/iam/docs/granting-changing-revoking-access).\n\nSet or modify labels\n\nAny configuration change leads to the\ncreation of a new revision. Subsequent revisions will also automatically get\nthis configuration setting unless you make explicit updates to change it.\n\nLabels you previously set for your Cloud Run functions using either\n`gcloud functions` commands or the Cloud Functions v2 API propagate to Cloud Run when you [deploy your functions in Cloud Run](/run/docs/deploy-functions).\n\nYou can set or modify labels using the Google Cloud console, the gcloud\ncommand line, or a YAML file when you\n[deploy a new revision](/run/docs/deploying#revision). \n\nConsole\n\n1. In the Google Cloud console, go to Cloud Run:\n\n [Go to Cloud Run](https://console.cloud.google.com/run)\n2. Check the checkbox at the left of the service you are setting the label\n on.\n\n3. Make sure the *Info Panel* at the far right is toggled on\n (**Show Info Panel**).\n\n4. Click **Labels** to display the labels pane.\n\n5. To edit an existing label key value, locate the label and change the\n *Value* as desired.\n\n6. To set a new label on the service, click **Add Label** and supply the key\n and the value.\n\n7. Click **Save**\n\ngcloud\n\nYou can update labels for a service using the command:\n\n\u003cbr /\u003e\n\n```bash\ngcloud run services update SERVICE --update-labels KEY=VALUE\n```\n\n\u003cbr /\u003e\n\nTo update more than one label, supply a comma delimited list of key/value\npairs. Note that the `update-labels` command sets a new value for the label\nkey if the label already exists, otherwise it creates a new label.\n\nReplace\n\n- \u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e with name of your Cloud Run service\n- \u003cvar translate=\"no\"\u003eKEY\u003c/var\u003e with the name of your label key\n- \u003cvar translate=\"no\"\u003eVALUE\u003c/var\u003e with the value for the key\n\nYou can also set labels during [deployment](/run/docs/deploying#service):\n\n\u003cbr /\u003e\n\n```bash\ngcloud run deploy SERVICE --image IMAGE --labels KEY=VALUE\n```\n\n\u003cbr /\u003e\n\nTo create more than one label during deployment, supply a comma delimited\nlist of key/value pairs.\n\nYAML\n\n1. If you are creating a new service, skip this step.\n If you are updating an existing service, download its [YAML configuration](/run/docs/reference/yaml/v1):\n\n ```bash\n gcloud run services describe SERVICE --format export \u003e service.yaml\n ```\n2. Update the `labels` attributes in two places:\n\n ```yaml\n apiVersion: serving.knative.dev/v1\n kind: Service\n metadata:\n name: SERVICE\n labels:\n LABEL: VALUE\n spec:\n template:\n metadata:\n labels:\n LABEL: VALUE\n name: REVISION\n ```\n\n Replace\n - \u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e with the name of your Cloud Run service\n - \u003cvar translate=\"no\"\u003eLABEL\u003c/var\u003e with the name of the label\n - \u003cvar translate=\"no\"\u003eVALUE\u003c/var\u003e with the desired value\n - \u003cvar translate=\"no\"\u003eREVISION\u003c/var\u003e with a new revision name or delete it (if present). If you supply a new revision name, it **must** meet the following criteria:\n - Starts with \u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e`-`\n - Contains only lowercase letters, numbers and `-`\n - Does not end with a `-`\n - Does not exceed 63 characters\n\n `metadata.labels` sets labels on the service object, while\n `spec.template.metadata.label` sets labels on the created revision.\n Only labels set on the revision are passed to logs and billing.\n3. Create or update the service using the following command:\n\n ```bash\n gcloud run services replace service.yaml\n ```\n\nTerraform\n\n\nTo learn how to apply or remove a Terraform configuration, see\n[Basic Terraform commands](/docs/terraform/basic-commands).\nAdd the following to a [`google_cloud_run_v2_service`](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloud_run_v2_service) resource in your Terraform configuration: \n\n\u003cbr /\u003e\n\n resource \"google_cloud_run_v2_service\" \"default\" {\n name = \"cloudrun-service-labels\"\n location = \"us-central1\"\n\n deletion_protection = false # set to \"true" in productiontemplate {\n containers {\n image ="us-docker.pkg.dev/cloudrun/container/hello\"\n }\n # Labels\n labels = {\n foo : \"bar\"\n baz : \"quux\"\n }\n }\n }\n\nThe preceding snippet adds two labels, `foo` (whose value is `bar`) and `baz`\n(whose value is `quux`), to your Cloud Run instance.\n\nAdding the labels under `template` sets the labels for the revision: only\nlabels set for the revision are passed to logs and billing. If you add the\nlabels to a location other than under `template`, the label is set for the\nservice not the revision.\n\nReplace the:\n\n- `name` property with the name of your service.\n- `location` property with the location used for your service.\n- `image` property with your container image.\n- `foo` and `baz` with your own label names.\n- `bar` and `quux` with your own label values.\n\nList services by label\n\nYou can list services by label using a\n[Google Cloud CLI filter](/sdk/gcloud/reference/topic/filters):\n\n\u003cbr /\u003e\n\n```bash\n gcloud run services list --filter metadata.labels.LABEL=VALUE\n \n```\n\n\u003cbr /\u003e\n\nReplace:\n\n- \u003cvar translate=\"no\"\u003eLABEL\u003c/var\u003e with the name of the label\n- \u003cvar translate=\"no\"\u003eVALUE\u003c/var\u003e with the value to include in your filtered list\n\nDelete a label on a service\n\nYou can use the console or the command line delete labels on a service. \n\nConsole\n\n1. In the Google Cloud console, go to Cloud Run:\n\n [Go to Cloud Run](https://console.cloud.google.com/run)\n2. Check the checkbox at the left of the service you are deleting the label\n from.\n\n3. Make sure the *Info Panel* at the far right is toggled on\n (**Show Info Panel**).\n\n4. Click **Labels** to display the labels pane.\n\n5. Locate the label you want to delete.\n\n6. Hover your cursor to the right of the *Value* textbox for the label to\n display the trash icon, and click the trash icon.\n\n7. Click **Save**\n\ngcloud\n\nTo clear all labels from a service:\n\n\u003cbr /\u003e\n\n```bash\ngcloud run services update SERVICE --clear-labels\n```\n\n\u003cbr /\u003e\n\nTo delete specific labels from a service, supply a comma delimited list of\nkeys:\n\n\u003cbr /\u003e\n\n```bash\ngcloud run services update SERVICE --remove-labels LABEL\n```\n\n\u003cbr /\u003e\n\nReplace\n\n- \u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e with name of your Cloud Run service\n- \u003cvar translate=\"no\"\u003eLABEL\u003c/var\u003e with the name of your label"]]