# 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
하단에서 gserviceaccount.com을 확인합니다. 이렇게 하면 gserviceaccount.com 도메인의 구성원만 IAM 정책에 제공되도록 지정됩니다.
정책이 예상한 대로 작동하는지 확인하려면 현재 디렉터리에 다음 Terraform main.tf 파일을 만듭니다. nano, vim, Cloud Shell 편집기를 사용하여 policy-library/main.tf를 만들 수 있습니다.
IAM 정책 binding에 제공한 이메일 주소가 서비스 계정에 속하지 않으므로 이 계획은 설정된 제약조건을 위반합니다.
[{"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"}]
다른 도메인(이메일)을 허용하려면 policy-library/policies/constraints/iam_service_accounts_only.yaml을 수정하고 이메일 도메인을 도메인 허용 목록에 추가합니다. 다음 예시에서는 example.com이 추가되었지만 고유 이메일 주소의 도메인을 입력할 수 있습니다.
"Error 403: The caller does not have permission, forbidden" 오류가 표시되면 policy-library/main.tf에서 PROJECT_ID를 프로젝트 이름으로 바꾸지 않았거나 지정한 프로젝트에 필요한 권한이 없기 때문입니다.
프로젝트 이름 또는 권한을 수정한 후(resourcemanager.projects.getIamPolicy 및 resourcemanager.projects.get) 다시 돌아가서 Terraform 계획을 내보낸 다음 Terraform 계획을 JSON으로 변환합니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(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."]]