Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Nesta página, você aprenderá a gerenciar unidades de locação do seu serviço. Uma unidade de locação é um recurso leve que representa a relação entre um consumidor de serviço e um serviço gerenciado. Cada consumidor de serviço pode ter apenas uma unidade de locação ativa para um serviço gerenciado. Esse é um recurso fornecido pela infraestrutura de serviços.
O nome do recurso de uma unidade de locação tem o seguinte formato:
services/{your service name}/projects/{consumer project number}/tenancyUnits/{id}
O ID de uma unidade de locação é gerado automaticamente quando você a cria. Também é
possível fornecer um ID ao chamar
o método
services.tenancyUnits.create. Se você fornecer um ID, ele precisará ser globalmente exclusivo no escopo do
serviço gerenciado entre todos os consumidores de serviço.
Os exemplos nesta página usam chamadas diretas para a API REST da
Gestão de consumidores de serviço.
Para uso em produção, recomendamos o uso de bibliotecas de cliente fornecidas pelo
Google para melhorar a usabilidade e a confiabilidade.
Antes de começar
A API Service Consumer Management destina-se ao uso com serviços gerenciados e projetos de produtor de serviço. Você precisa já ter um Google Cloud projeto e um serviço gerenciado (como um serviço criado usando o Cloud Endpoints) nesse projeto.
Para usar unidades de locação, a API Service Consumer Management precisa criar projetos de locatário na sua organização de produtores de serviço. Verifique se você tem cota suficiente
para o número necessário de projetos de locatário para os consumidores do
seu serviço.
Cada projeto de locatário criado em uma unidade de locação precisa estar também
em uma pasta especificada
como parte da configuração do projeto de locatário. Por isso, você precisa de uma organização para usar unidades de locação.
Autenticação
Select the tabs for how you plan to access the API:
gcloud
Instale a CLI do Google Cloud.
Após a instalação,
inicialize a Google Cloud CLI executando o seguinte comando:
Para usar bibliotecas de cliente em um ambiente de desenvolvimento local, instale e inicialize o
gcloud CLI e configure o Application Default Credentials com suas credenciais de usuário.
As unidades de locação e os projetos de locatário normalmente são criados quando
são criados recursos no seu próprio serviço que dependem de outros recursos
do Google Cloud a serem provisionados para os consumidores.
POST https://serviceconsumermanagement.googleapis.com/v1/services/service.example.com/projects/12345678901/tenancyUnits
Aqui, "projects/12345678901" representa o consumidor de serviço, e
service.example.com é o nome do serviço.
A estrutura de dados retornada tem o nome da unidade de locação, com um código exclusivo gerado que pode ser usado para acessá-la. Neste exemplo, o nome gerado é services/your-service.example.com/projects/12345678901/tenancyUnits/absdef.
Como adicionar um projeto de locatário
Agora você pode adicionar um projeto para o usuário. Para adicionar um novo projeto de locatário à unidade de locação criada na etapa anterior, use o método services.tenancyUnits.addProject:
POST https://serviceconsumermanagement.googleapis.com/v1/services/your-service.example.com/projects/12345678901/tenancyUnits/absdef:addProject
O valor tag é um identificador que você fornece para o projeto na unidade de locação. Pode ser o que você quiser (aqui é tag1), como uma região, uma rede de consumidores ou apenas um ID de string.
Essa chamada retorna uma operação de longa duração que pode ser consultada para verificar se a criação do projeto foi bem-sucedida.
Se você precisar aplicar uma configuração diferente, por exemplo, para adicionar novos serviços gerenciados, poderá chamar o método services.tenancyUnits.applyProjectConfig.
Como procurar suas unidades de locação
Encontrar uma unidade de locação para um consumidor de serviço
Para encontrar uma unidade de locação para um consumidor de serviço específico, use o método services.tenancyUnits.list, especificando o número do projeto do consumidor de serviço:
GET https://serviceconsumermanagement.googleapis.com/v1/services/your-service.example.com/projects/12345678901/tenancyUnits
Pesquisar unidades de locação
Use o
método services.search
para procurar unidades de locação definidas
para o serviço. Por exemplo, a seguinte consulta retornará todas as unidades que têm um projeto com a tag "tag1".
GET https://serviceconsumermanagement.googleapis.com/v1/services/your-service.example.com:search?query=tenant_resources.tag=tag1
Como limpar unidades de locação
Quando um consumidor de serviço para de usar seu serviço, você precisa remover a
unidade de locação para liberar recursos e garantir que os dados do usuário sejam excluídos.
Remover projetos de locatário
Você precisa excluir todos os projetos de locatário antes de excluir a unidade de
locação correspondente. Use o
método services.tenancyUnits.removeProject
para excluir um projeto de locatário e todos os recursos nele:
POST https://serviceconsumermanagement.googleapis.com/v1/services/your-service.example.com/projects/12345678901/tenancyUnits/absdef:removeProject
Excluir uma unidade de locação
Depois de excluir todos os projetos de locatário em uma unidade de locação ou quando
todos eles estiverem no estado DELETED, exclua a unidade de locação usando o
método services.tenancyUnits.delete:
[[["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-03 UTC."],[],[],null,["# Managing Tenancy Units\n\nThis page shows you how to manage [tenancy units](/service-infrastructure/docs/glossary#tenancy) for\nyour service. A [tenancy unit](/service-infrastructure/docs/glossary#tenancy) is a lightweight resource\nthat represents the relationship between a\n[service consumer](/service-infrastructure/docs/glossary#consumer) and a\n[managed service](/service-infrastructure/docs/glossary#managed). Each service consumer can have\nonly one active tenancy unit for a managed service. This is a feature\nprovided by Service Infrastructure.\n\nThe resource name of a tenancy unit has the following format: \n\n services/{your service name}/projects/{consumer project number}/tenancyUnits/{id}\n\nThe ID of a tenancy unit is auto-generated when you create it. You can also\nprovide an ID when you call the\n[`services.tenancyUnits.create`](/service-infrastructure/docs/service-consumer-management/reference/rest/v1/services.tenancyUnits/create)\nmethod. If you provide an ID, it must be globally unique within the scope of\nyour managed service across all service consumers.\n\nThe examples on this page use direct calls to the Service Consumer Management\n[REST API](/service-infrastructure/docs/service-consumer-management/reference/rest).\nFor production usage, we recommend you use Google-provided client libraries\nfor better usability and reliability.\n\nBefore you begin\n----------------\n\n- The Service Consumer Management API is intended for use with [managed services](/service-infrastructure/docs/glossary#managed) and [service producer](/service-infrastructure/docs/glossary#producer) projects. You'll need to already have a Google Cloud project and a managed service (such as a service created using [Cloud Endpoints](/endpoints/docs)) in that project.\n- To use tenancy units, the Service Consumer Management API needs to create tenant projects in your service producer organization. Make sure that you have enough quota for the necessary number of tenant projects for your service's consumers.\n- To create and delete tenancy units, follow the initial setup instructions in [Getting Started with the Service Consumer Management API](/service-infrastructure/docs/service-consumer-management/getting-started).\n- Each tenant project created in a tenancy unit must also be in a [folder](/resource-manager/docs/creating-managing-folders) that you specify as part of the tenant project configuration. Because of this, you need an [Organization](/resource-manager/docs/creating-managing-organization) to use tenancy units.\n\nAuthentication\n--------------\n\nSelect the tabs for how you plan to access the API: \n\n### gcloud\n\n\n[Install](/sdk/docs/install) the Google Cloud CLI.\n\nAfter installation,\n[initialize](/sdk/docs/initializing) the Google Cloud CLI by running the following command:\n\n```bash\ngcloud init\n```\n\n\nIf you're using an external identity provider (IdP), you must first\n[sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n### Client libraries\n\n\nTo use client libraries in a local development environment, install and initialize the\ngcloud CLI, and then set up Application Default Credentials with your user\ncredentials.\n\n1. [Install](/sdk/docs/install) the Google Cloud CLI.\n2. If you're using an external identity provider (IdP), you must first [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n3. If you're using a local shell, then create local authentication credentials for your user account: \n\n```bash\ngcloud auth application-default login\n```\n4. You don't need to do this if you're using Cloud Shell.\n5. If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have [signed in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n\nFor more information, see\n[Set up ADC for a local development environment](/docs/authentication/set-up-adc-local-dev-environment)\nin the Google Cloud authentication documentation.\n\n### REST\n\n\nTo use the REST API in a local development environment, you use the credentials you provide to\nthe gcloud CLI.\n\n1. [Install](/sdk/docs/install) the Google Cloud CLI.\n2. If you're using an external identity provider (IdP), you must first [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n\nFor more information, see\n[Authenticate for using REST](/docs/authentication/rest)\nin the Google Cloud authentication documentation.\n\n\nFor information about setting up authentication for a production\nenvironment, see\n[Set up Application Default Credentials for code running on\nGoogle Cloud](/docs/authentication/set-up-adc-attached-service-account)\nin the Google Cloud authentication documentation.\n\n\u003cbr /\u003e\n\nCreating a tenancy unit\n-----------------------\n\nTenancy units and the tenant projects in them are normally created when\nresources in your own service are created that depend on additional\nGoogle Cloud resources to be provisioned for the consumers.\n\nYou create a tenancy unit using the\n[`services.tenancyUnits.create` method](/service-infrastructure/docs/service-consumer-management/reference/rest/v1/services.tenancyUnits/create): \n\n POST https://serviceconsumermanagement.googleapis.com/v1/services/service.example.com/projects/12345678901/tenancyUnits\n\nHere, 'projects/12345678901' represents the service consumer, and\n`service.example.com` is the name of your service.\n\nThe returned data structure has the name of the tenancy unit, with a generated\nunique id that can be used to access it. In this example, the generated name is\n`services/your-service.example.com/projects/12345678901/tenancyUnits/absdef`.\n\nAdding a tenant project\n-----------------------\n\nYou can now add a project for the user. To add a new tenant project to the\ntenancy unit created in the previous step, use the\n[`services.tenancyUnits.addProject` method](/service-infrastructure/docs/service-consumer-management/reference/rest/v1/services.tenancyUnits/addProject): \n\n POST https://serviceconsumermanagement.googleapis.com/v1/services/your-service.example.com/projects/12345678901/tenancyUnits/absdef:addProject\n\nwith the following data: \n\n {\"tag\":\"tag1\", \"project_config\":{\"folder\":\"folders/9876543210\", \"tenant_project_policy\":{\"policy_bindings\":{\"role\":\"roles/owner\", \"members\":\"user:bob@example.com\"}}, \"billing_config\":{\"billing_account\":\"billingAccounts/123456-472F22-28F9AA\"}}}\n\nThe `tag` value is an identifier you provide for the project within the tenancy\nunit: this can be anything you like (here it's `tag1`), such as a region, a\nconsumer network, or just a string ID.\n\nThis call returns a long running operation that you can query to find if the\nproject creation was successful.\n\nIf you need to apply a different configuration, for example to add new managed\nservices, you can call the\n[`services.tenancyUnits.applyProjectConfig`](/service-infrastructure/docs/service-consumer-management/reference/rest/v1/services.tenancyUnits/applyProjectConfig)\nmethod.\n\nSearching your tenancy units\n----------------------------\n\n### Find a tenancy unit for a service consumer\n\nTo find a tenancy unit for a particular service consumer, use the\n[`services.tenancyUnits.list` method](/service-infrastructure/docs/service-consumer-management/reference/rest/v1/services.tenancyUnits/list),\nspecifying their service consumer project number: \n\n GET https://serviceconsumermanagement.googleapis.com/v1/services/your-service.example.com/projects/12345678901/tenancyUnits\n\n### Search tenancy units\n\nYou can use the\n[`services.search` method](/service-infrastructure/docs/service-consumer-management/reference/rest/v1/services/search)\nto search for tenancy units defined\nfor your service. For example, the following query will return all units that\ncontain a project with the tag 'tag1': \n\n GET https://serviceconsumermanagement.googleapis.com/v1/services/your-service.example.com:search?query=tenant_resources.tag=tag1\n\nCleaning up tenancy units\n-------------------------\n\nWhen a service consumer stops using your service, you need to remove its\ntenancy unit to free up resources and ensure the user data is deleted.\n\n### Remove tenant projects\n\nYou need to delete all tenant projects before you delete the corresponding\ntenancy unit. You should use the\n[`services.tenancyUnits.removeProject`](/service-infrastructure/docs/service-consumer-management/reference/rest/v1/services.tenancyUnits/removeProject)\nmethod to delete a tenant project and all resources in it: \n\n POST https://serviceconsumermanagement.googleapis.com/v1/services/your-service.example.com/projects/12345678901/tenancyUnits/absdef:removeProject\n\n### Delete a tenancy unit\n\nAfter you have deleted all tenant projects in a tenancy unit, or all of them\nare in the `DELETED` state, you can delete the tenancy unit using the\n[`services.tenancyUnits.delete` method](/service-infrastructure/docs/service-consumer-management/reference/rest/v1/services.tenancyUnits/delete): \n\n DELETE https://serviceconsumermanagement.googleapis.com/v1/services/your-service.example.com/projects/12345678901/tenancyUnits/absdef"]]