Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Panduan memulai ini menunjukkan cara menerapkan batasan yang memberlakukan pembatasan domain. Anda akan menguji batasan tersebut dan sengaja menampilkan error. Kemudian, ubah batasan agar domain Anda dinyatakan lulus.
resourcemanager.projects.getIamPolicy – Izin ini dapat diberikan dengan peran Security Reviewer untuk organisasi.
resourcemanager.projects.get – Izin ini dapat diberikan dengan peran Project Viewer untuk organisasi.
Untuk membantu Anda memulai dengan cepat, petunjuk ini menggunakan Cloud Shell yang telah diinstal sebelumnya dengan Terraform, dan dengan repositori Library Kebijakan yang di-clone. Petunjuk ini mengasumsikan bahwa Anda sudah memiliki akun Google Cloud .
Panduan memulai
Buka Cloud Shell dan buat clone library kebijakan.
# 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
Perhatikan gserviceaccount.com di bagian bawah. Ini menetapkan bahwa hanya anggota dari domain gserviceaccount.com yang boleh ada dalam kebijakan IAM.
Untuk memastikan bahwa kebijakan berfungsi seperti yang diharapkan, buat file main.tf Terraform berikut di direktori saat ini. Anda dapat menggunakan nano, vim, atau Cloud Shell Editor untuk membuat policy-library/main.tf.
Karena alamat email yang Anda berikan di binding kebijakan IAM bukan milik akun layanan, rencana tersebut melanggar batasan yang Anda siapkan.
[{"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"}]
Untuk mengizinkan domain lain (email Anda), edit policy-library/policies/constraints/iam_service_accounts_only.yaml dan tambahkan domain email Anda ke daftar domain yang diizinkan. Dalam contoh berikut, kami telah menambahkan example.com, tetapi Anda akan memasukkan domain untuk alamat email Anda sendiri:
Jika Anda menerima error berikut, "Error 403: The caller does not have permission, forbidden", berarti Anda tidak mengganti PROJECT_ID di policy-library/main.tf dengan nama project Anda, atau Anda tidak memiliki izin yang diperlukan pada project yang ditentukan.
Setelah mengedit nama dan/atau izin project (resourcemanager.projects.getIamPolicy dan resourcemanager.projects.get), kembali dan ekspor rencana Terraform lagi, lalu konversikan rencana Terraform ke JSON.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-08-18 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."]]