Guia de início rápido do comando gcloud beta terraform vet
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Neste guia de início rápido, mostramos como aplicar uma restrição que impõe uma restrição de domínio. Você vai testar essa restrição e gerar um erro intencionalmente. Em seguida, vai modificar a restrição para que seu domínio seja aprovado.
resourcemanager.projects.getIamPolicy: essa permissão pode ser concedida com o papel de Revisor de segurança da organização.
resourcemanager.projects.get: esta permissão pode ser concedida com o papel de Visualizador do projeto da organização.
Para começar rapidamente, estas instruções usam um Cloud Shell pré-instalado com o Terraform e um repositório clonado da Biblioteca de políticas. Para seguir as instruções, é necessário ter uma conta do Google Cloud.
Guia de início rápido
Acesse o Cloud Shell e clone a biblioteca de políticas.
# This constraint checks that all IAM policy members are in the# "gserviceaccount.com" domain.apiVersion:constraints.gatekeeper.sh/v1alpha1kind:GCPIAMAllowedPolicyMemberDomainsConstraintV2metadata:name:service_accounts_onlyannotations:description:ChecksthatmembersthathavebeengrantedIAMrolesbelongtoallowlisteddomains.spec:severity:highmatch:target: # {"$ref":"#/definitions/io.k8s.cli.setters.target"}-"organizations/**"parameters:domains:-gserviceaccount.com
Observe o ícone gserviceaccount.com na parte inferior. Ela especifica que apenas membros do domínio gserviceaccount.com podem estar presentes em uma política do IAM.
Para verificar se a política funciona conforme o esperado, crie o seguinte arquivo main.tf do Terraform no diretório atual. Você pode usar o nano, o vim ou o editor do Cloud Shell para criar policy-library/main.tf.
Como o endereço de e-mail fornecido na vinculação da política do IAM não pertence a uma conta de serviço, o plano viola a restrição configurada.
[{"constraint":"GCPIAMAllowedPolicyMemberDomainsConstraintV2.service_accounts_only","constraint_config":{"api_version":"constraints.gatekeeper.sh/v1alpha1","kind":"GCPIAMAllowedPolicyMemberDomainsConstraintV2","metadata":{"annotations":{"description":"Checks that members that have been granted IAM roles belong to allowlisted domains.","validation.gcp.forsetisecurity.org/originalName":"service_accounts_only","validation.gcp.forsetisecurity.org/yamlpath":"policies/constraints/iam_service_accounts_only.yaml"},"name":"service-accounts-only"},"spec":{"match":{"target":["organizations/**"]},"parameters":{"domains":["gserviceaccount.com"]},"severity":"high"}},"message":"IAM policy for //cloudresourcemanager.googleapis.com/projects/PROJECT_ID contains member from unexpected domain: user:user@example.com","metadata":{"ancestry_path":"organizations/ORG_ID/projects/PROJECT_ID","constraint":{"annotations":{"description":"Checks that members that have been granted IAM roles belong to allowlisted domains.","validation.gcp.forsetisecurity.org/originalName":"service_accounts_only","validation.gcp.forsetisecurity.org/yamlpath":"policies/constraints/iam_service_accounts_only.yaml"},"labels":{},"parameters":{"domains":["gserviceaccount.com"]}},"details":{"member":"user:user@example.com","resource":"//cloudresourcemanager.googleapis.com/projects/PROJECT_ID"}},"resource":"//cloudresourcemanager.googleapis.com/projects/PROJECT_ID","severity":"high"}]
Para permitir outro domínio (seu e-mail), edite policy-library/policies/constraints/iam_service_accounts_only.yaml e anexe seu domínio de e-mail à lista de permissões de domínios. No exemplo a seguir, adicionamos example.com, mas você deve inserir o domínio do seu próprio endereço de e-mail:
Se você receber o seguinte erro, "Error 403: The caller does not have permission, forbidden", significa que não substituiu PROJECT_ID em policy-library/main.tf pelo nome do seu projeto ou que não tem as permissões necessárias no projeto especificado.
Depois de editar o nome e/ou as permissões do projeto (resourcemanager.projects.getIamPolicy e resourcemanager.projects.get), volte e exporte o plano do Terraform novamente. Em seguida, converta-o em JSON.
[[["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-08-07 UTC."],[[["\u003cp\u003eThis quickstart demonstrates how to apply a constraint to enforce a domain restriction on IAM policy members, ensuring they belong to specified domains.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves cloning a policy library, copying a sample constraint, and using Terraform to create and validate an IAM policy binding against the constraint.\u003c/p\u003e\n"],["\u003cp\u003eAn initial test with a non-service account email address demonstrates how the constraint correctly detects and reports a policy violation.\u003c/p\u003e\n"],["\u003cp\u003eYou can modify the constraint to allow additional domains by updating the \u003ccode\u003edomains\u003c/code\u003e list in the constraint's YAML file.\u003c/p\u003e\n"],["\u003cp\u003eThe Pre-GA products and features within this content are available "as is" with potentially limited support, and are subject to the "Pre-GA Offerings Terms".\u003c/p\u003e\n"]]],[],null,["# gcloud beta terraform vet quickstart\n\n| **Preview**\n|\n|\n| This product or feature is subject to the \"Pre-GA Offerings Terms\" in the General Service Terms section\n| of the [Service Specific Terms](/terms/service-terms#1).\n|\n| Pre-GA products and features are available \"as is\" and might have limited support.\n|\n| For more information, see the\n| [launch stage descriptions](/products#product-launch-stages).\n\nThis quickstart shows you how to apply a constraint that enforces a domain restriction. You'll test that constraint and intentionally throw an error. Then you'll modify the constraint so that your domain passes.\n\nBefore you begin\n----------------\n\n- You need a [Google Cloud project](/resource-manager/docs/creating-managing-projects).\n- You need the following [Identity and Access Management (IAM) permissions](/resource-manager/docs/access-control-proj) for that project:\n\n - `resourcemanager.projects.getIamPolicy` -- This permission can be granted with the Security Reviewer role for the organization.\n - `resourcemanager.projects.get` -- This permission can be granted with the Project Viewer role for the organization.\n\nTo get you started quickly, these instructions use a Cloud Shell that's pre-installed with Terraform, and with a [cloned Policy Library repository](/docs/terraform/policy_validation/create_policy_library#duplicate_the_sample_library). The instructions assume you already have a Google Cloud account.\n\nQuickstart\n----------\n\n1. Go to the Cloud Shell and clone the policy library.\n\n [Clone policy library](https://console.cloud.google.com/cloudshell/open?cloudshell_git_repo=https://github.com/GoogleCloudPlatform/policy-library.git)\n2. Copy the sample IAM domain restriction constraint into\n the `policies/constraints` directory.\n\n cp samples/iam_service_accounts_only.yaml policies/constraints\n\n3. Examine the constraint you copied by printing it to the terminal.\n\n cat policies/constraints/iam_service_accounts_only.yaml\n\n The output looks like this: \n\n # This constraint checks that all IAM policy members are in the\n # \"gserviceaccount.com\" domain.\n apiVersion: constraints.gatekeeper.sh/v1alpha1\n kind: GCPIAMAllowedPolicyMemberDomainsConstraintV2\n metadata:\n name: service_accounts_only\n annotations:\n description: Checks that members that have been granted IAM roles belong to allowlisted\n domains.\n spec:\n severity: high\n match:\n target: # {\"$ref\":\"#/definitions/io.k8s.cli.setters.target\"}\n - \"organizations/**\"\n parameters:\n domains:\n - gserviceaccount.com\n\n Notice `gserviceaccount.com` at the bottom. This specifies that only members\n from the `gserviceaccount.com` domain can be present in an IAM\n policy.\n4. To verify that the policy works as expected, create the following Terraform\n `main.tf` file in the current directory. You can use nano, vim, or the\n Cloud Shell Editor to create `policy-library/main.tf`.\n\n terraform {\n required_providers {\n google = {\n source = \"hashicorp/google\"\n version = \"~\u003e 3.84\"\n }\n }\n }\n\n resource \"google_project_iam_binding\" \"sample_iam_binding\" {\n project = \"\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e\"\n role = \"roles/viewer\"\n\n members = [\n \"user:\u003cvar translate=\"no\"\u003eEMAIL_ADDRESS\u003c/var\u003e\"\n ]\n }\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003e\u003ccode translate=\"no\" dir=\"ltr\"\u003ePROJECT_ID\u003c/code\u003e\u003c/var\u003e: your project ID.\n - \u003cvar translate=\"no\"\u003e\u003ccode translate=\"no\" dir=\"ltr\"\u003eEMAIL_ADDRESS\u003c/code\u003e\u003c/var\u003e: a sample email address. This can be any valid email address. For example, `user@example.com`.\n5. Initialize Terraform and generate a Terraform plan using the following:\n\n terraform init\n\n6. Export the Terraform plan, if asked, click **Authorize** when prompted:\n\n terraform plan -out=test.tfplan\n\n7. Convert the Terraform plan to JSON:\n\n terraform show -json ./test.tfplan \u003e ./tfplan.json\n\n8. Install the terraform-tools component:\n\n sudo apt-get install google-cloud-sdk-terraform-tools\n\n9. Enter the following command to validate that your Terraform plan complies with your policies:\n\n gcloud beta terraform vet tfplan.json --policy-library=. --format=json\n\n Since the email address you provided in the IAM policy binding does not belong to a service account, the plan violates the constraint you set up. \n\n ```json\n [\n {\n \"constraint\": \"GCPIAMAllowedPolicyMemberDomainsConstraintV2.service_accounts_only\",\n \"constraint_config\": {\n \"api_version\": \"constraints.gatekeeper.sh/v1alpha1\",\n \"kind\": \"GCPIAMAllowedPolicyMemberDomainsConstraintV2\",\n \"metadata\": {\n \"annotations\": {\n \"description\": \"Checks that members that have been granted IAM roles belong to allowlisted domains.\",\n \"validation.gcp.forsetisecurity.org/originalName\": \"service_accounts_only\",\n \"validation.gcp.forsetisecurity.org/yamlpath\": \"policies/constraints/iam_service_accounts_only.yaml\"\n },\n \"name\": \"service-accounts-only\"\n },\n \"spec\": {\n \"match\": {\n \"target\": [\n \"organizations/**\"\n ]\n },\n \"parameters\": {\n \"domains\": [\n \"gserviceaccount.com\"\n ]\n },\n \"severity\": \"high\"\n }\n },\n \"message\": \"IAM policy for //cloudresourcemanager.googleapis.com/projects/\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e contains member from unexpected domain: user:user@example.com\",\n \"metadata\": {\n \"ancestry_path\": \"organizations/\u003cvar translate=\"no\"\u003eORG_ID\u003c/var\u003e/projects/\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e\",\n \"constraint\": {\n \"annotations\": {\n \"description\": \"Checks that members that have been granted IAM roles belong to allowlisted domains.\",\n \"validation.gcp.forsetisecurity.org/originalName\": \"service_accounts_only\",\n \"validation.gcp.forsetisecurity.org/yamlpath\": \"policies/constraints/iam_service_accounts_only.yaml\"\n },\n \"labels\": {},\n \"parameters\": {\n \"domains\": [\n \"gserviceaccount.com\"\n ]\n }\n },\n \"details\": {\n \"member\": \"user:user@example.com\",\n \"resource\": \"//cloudresourcemanager.googleapis.com/projects/\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e\"\n }\n },\n \"resource\": \"//cloudresourcemanager.googleapis.com/projects/\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e\",\n \"severity\": \"high\"\n }\n ]\n ```\n10. To allow another domain (your email), edit `policy-library/policies/constraints/iam_service_accounts_only.yaml` and append your email domain to the domains allowlist. In the following example, we've added \u003cvar translate=\"no\"\u003e\u003ccode translate=\"no\" dir=\"ltr\"\u003eexample.com\u003c/code\u003e\u003c/var\u003e, but you'd enter the domain for your own email address:\n\n apiVersion: constraints.gatekeeper.sh/v1alpha1\n kind: GCPIAMAllowedPolicyMemberDomainsConstraintV1\n metadata:\n name: service_accounts_only\n spec:\n severity: high\n match:\n target: [\"organizations/**\"]\n parameters:\n domains:\n - gserviceaccount.com\n - example.com\n\n11. Now validate your Terraform plan again, and this should result in no violations found:\n\n gcloud beta terraform vet tfplan.json --policy-library=. --format=json\n\n Expected output: \n\n ```json\n []\n ```\n\nTroubleshooting\n---------------\n\nIf you receive the following error, `\"Error 403: The caller does not have permission, forbidden\"`, then you either didn't replace \u003cvar translate=\"no\"\u003e\u003ccode translate=\"no\" dir=\"ltr\"\u003ePROJECT_ID\u003c/code\u003e\u003c/var\u003e in `policy-library/main.tf` with the name of your project, or you don't have the necessary permissions on the project you specified.\n\nAfter editing the project name and/or permissions (`resourcemanager.projects.getIamPolicy` and `resourcemanager.projects.get`), go back and export the Terraform plan again, and then convert the Terraform plan to JSON."]]