리소스 액세스 거부

이 페이지에서는 특정 Identity and Access Management(IAM) 권한을 사용하지 못하도록 방지하여 주 구성원 액세스를 거부하는 방법을 설명합니다.

IAM에서는 거부 정책을 사용하여 액세스를 거부합니다. 각 거부 정책은 Google Cloud 조직, 폴더, 프로젝트에 연결됩니다. 거부 정책에는 주 구성원을 식별하고 주 구성원이 사용할 수 없는 권한을 나열하는 거부 규칙이 포함됩니다.

거부 정책은 IAM 정책으로도 알려진 허용 정책과 구분됩니다. 허용 정책은 주 구성원에 IAM 역할을 부여하여 리소스에 대해 액세스 권한을 제공합니다.

Google Cloud CLI 또는 IAM v2 REST API를 사용하여 거부 정책을 관리할 수 있습니다.

시작하기 전에

  • IAM API 사용 설정

    API 사용 설정

  • 인증을 설정합니다.

    Select the tab for how you plan to use the samples on this page:

    gcloud

    다음 개발 환경 중 하나에서 이 페이지의 gcloud CLI 샘플을 사용할 수 있습니다.

    • Cloud Shell: gcloud CLI가 이미 설정된 온라인 터미널을 사용하려면 Cloud Shell을 활성화하세요.

      이 페이지 하단에서 Cloud Shell 세션이 시작되고 명령줄 프롬프트가 표시됩니다. 세션이 초기화되는 데 몇 초 정도 걸릴 수 있습니다.

    • 로컬 셸: 로컬 개발 환경에서 gcloud CLI를 사용하려면 gcloud CLI를 설치하고 초기화합니다.

    Terraform

    로컬 개발 환경에서 이 페이지의 Terraform 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 Google Cloud 인증 문서의 로컬 개발 환경 인증 설정을 참조하세요.

    Go

    이 페이지의 Go 샘플을 로컬 개발 환경에서 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 Google Cloud 인증 문서의 로컬 개발 환경 인증 설정을 참조하세요.

    Java

    이 페이지의 Java 샘플을 로컬 개발 환경에서 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 Google Cloud 인증 문서의 로컬 개발 환경 인증 설정을 참조하세요.

    Node.js

    이 페이지의 Node.js 샘플을 로컬 개발 환경에서 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 Google Cloud 인증 문서의 로컬 개발 환경 인증 설정을 참조하세요.

    Python

    이 페이지의 Python 샘플을 로컬 개발 환경에서 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 Google Cloud 인증 문서의 로컬 개발 환경 인증 설정을 참조하세요.

    REST

    로컬 개발 환경에서 이 페이지의 REST API 샘플을 사용하려면 gcloud CLI에 제공하는 사용자 인증 정보를 사용합니다.

      Google Cloud CLI를 설치한 후 다음 명령어를 실행하여 초기화합니다.

      gcloud init

    자세한 내용은 Google Cloud 인증 문서의 REST 사용 인증을 참조하세요.

  • 거부 정책 개요를 읽어봅니다.

필요한 역할

거부 정책을 관리하는 데 필요한 권한을 얻으려면 관리자에게 조직에서 다음 IAM 역할을 부여해 달라고 요청하세요.

역할 부여에 대한 자세한 내용은 액세스 관리를 참조하세요.

이러한 사전 정의된 역할에는 거부 정책 관리에 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 확장하세요.

필수 권한

거부 정책을 관리하려면 다음 권한이 필요합니다.

  • 거부 정책을 보려면 다음 권한이 필요합니다.
    • iam.denypolicies.get
    • iam.denypolicies.list
  • 거부 정책을 만들고, 업데이트하고, 삭제하려면 다음 권한이 필요합니다.
    • iam.denypolicies.create
    • iam.denypolicies.delete
    • iam.denypolicies.get
    • iam.denypolicies.update

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

거부할 권한 식별

거부 정책을 만들려면 먼저 거부할 권한과 이러한 권한을 거부할 주 구성원을 결정해야 합니다.

일부 권한만 거부할 수 있습니다. 거부할 수 있는 권한의 목록은 거부 정책에서 지원되는 권한을 참조하세요.

경우에 따라 권한 그룹을 사용하여 권한 집합을 거부할 수도 있습니다. 자세한 내용은 권한 그룹을 참조하세요.

권한 이름에 특별한 형식이 필요한 v2 REST API로 거부 정책을 관리합니다. 예를 들어 IAM 커스텀 역할 만들기 권한의 이름은 다음과 같이 지정됩니다.

  • v1 API: iam.roles.create
  • v2 API: iam.googleapis.com/roles.create

연결 지점 식별

각 거부 정책은 조직, 폴더 또는 프로젝트에 연결됩니다. 이러한 리소스 중 하나에 연결되면 거부 정책은 해당 프로젝트, 폴더 또는 조직의 모든 하위 수준 리소스에 상속됩니다. 거부 정책을 사용하려면 거부 정책이 연결된 리소스의 식별자가 필요합니다. 이를 연결 지점이라고 합니다. 이 식별자는 다음 표의 형식 중 하나를 사용합니다.

연결 지점 형식
조직

cloudresourcemanager.googleapis.com/organizations/ORG_ID
ORG_ID를 숫자 조직 ID로 바꿉니다. REST API의 경우 전체 값을 URL로 인코딩합니다.

gcloud CLI의 예시는 다음과 같습니다.
cloudresourcemanager.googleapis.com/organizations/123456789012

REST API의 예시는 다음과 같습니다.
cloudresourcemanager.googleapis.com%2Forganizations%2F123456789012

폴더

cloudresourcemanager.googleapis.com/folders/FOLDER_ID
FOLDER_ID를 숫자 폴더 ID로 바꿉니다. REST API의 경우 전체 값을 URL로 인코딩합니다.

gcloud CLI의 예시는 다음과 같습니다.
cloudresourcemanager.googleapis.com/folders/987654321098

REST API의 예시는 다음과 같습니다.
cloudresourcemanager.googleapis.com%2Ffolders%2F987654321098

프로젝트

cloudresourcemanager.googleapis.com/projects/PROJECT_ID
PROJECT_ID를 영숫자 또는 숫자 프로젝트 ID로 바꿉니다. REST API의 경우 전체 값을 URL로 인코딩합니다.

gcloud CLI의 예시는 다음과 같습니다.
cloudresourcemanager.googleapis.com/projects/my-project

REST API의 예시는 다음과 같습니다.
cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project

거부 정책 만들기

조직, 폴더, 프로젝트에 거부 정책을 추가할 수 있습니다. 각 리소스에 거부 정책을 최대 500개까지 사용할 수 있습니다.

거부 정책에는 다음을 지정하는 거부 규칙이 포함됩니다.

  • 거부할 권한입니다.
  • 이러한 권한이 거부된 주 구성원입니다.
  • 선택사항: 권한 거부에서 제외할 주 구성원입니다.

    예를 들어 그룹에 권한을 거부할 수 있지만 해당 그룹에 속하는 특정 사용자를 제외할 수 있습니다.

  • 선택사항: 주 구성원이 권한을 사용할 수 없는 경우를 지정하는 조건 표현식입니다. 거부 정책에서 조건 표현식은 리소스 태그에 대한 함수만 사용할 수 있습니다. 다른 함수 및 연산자는 지원되지 않습니다.

각 리소스는 연결된 모든 거부 정책 간에 거부 정책을 최대 500개까지 사용할 수 있습니다.

거부 정책은 리소스 계층을 통해 상속됩니다. 예를 들어 조직 수준에서 권한을 거부하는 경우 해당 권한이 조직 내의 폴더 및 프로젝트에서 그리고 각 프로젝트 내의 서비스 특정 리소스에서 거부됩니다.

거부 정책은 허용 정책을 재정의합니다. 주 구성원에 특정 권한이 포함된 역할이 부여되었지만 거부 정책에 주 구성원이 해당 권한을 사용할 수 없도록 지정된 경우 주 구성원이 권한을 사용할 수 없습니다.

gcloud

리소스에 대해 거부 정책을 만들려면 정책이 포함된 JSON 파일 만들기로 시작합니다. 거부 정책에는 다음 형식이 사용됩니다.

{
  "displayName": "POLICY_NAME",
  "rules": [
    {
      "denyRule": DENY_RULE_1
    },
    {
      "denyRule": DENY_RULE_2
    },
    {
      "denyRule": DENY_RULE_N
    }
  ]
}

다음 값을 제공합니다.

  • POLICY_NAME: 거부 정책의 표시 이름입니다.
  • DENY_RULE_1, DENY_RULE_2, ...DENY_RULE_N: 정책의 거부 규칙입니다. 각 거부 규칙에는 다음 필드가 포함될 수 있습니다.

    • deniedPermissions: 지정된 주 구성원이 사용할 수 없는 권한 목록입니다. 권한은 거부 정책에서 지원되어야 합니다.

      경우에 따라 권한 그룹을 사용하여 권한 집합을 거부할 수도 있습니다. 자세한 내용은 권한 그룹을 참조하세요.

    • deniedPrincipals: 지정된 권한을 사용할 수 없는 주 구성원의 목록입니다. 주 구성원 식별자에 대해 v2 API 형식을 사용합니다.
    • exceptionPrincipals: (선택사항) 주 구성원이 deniedPrincipals에 포함된 경우에도 지정된 권한을 사용할 수 있는 주 구성원 목록입니다. 예를 들어 이 필드를 사용하여 거부된 그룹에 속하는 특정 사용자에 대해 예외를 설정할 수 있습니다. 주 구성원 식별자에 대해 v2 API 형식을 사용합니다.
    • denialCondition: (선택사항) 주 구성원이 권한을 사용할 수 없는 경우를 지정하는 조건 표현식입니다. 다음 필드가 포함됩니다.

    거부 규칙 예시는 일반 사용 사례를 참조하세요.

예를 들어 다음 거부 정책에는 lucian@example.com 사용자에 대해 하나의 권한을 거부하는 하나의 거부 규칙이 포함됩니다.

{
  "displayName": "My deny policy.",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": [
          "principal://goog/subject/lucian@example.com"
        ],
        "deniedPermissions": [
          "iam.googleapis.com/roles.create"
        ]
      }
    }
  ]
}

그런 후 gcloud iam policies create 명령어를 실행합니다.

gcloud iam policies create POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --policy-file=POLICY_FILE

다음 값을 제공합니다.

  • POLICY_ID: 거부 정책의 식별자입니다.

  • ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

  • POLICY_FILE: 거부 정책을 포함하는 JSON 파일의 파일 경로입니다.

기본적으로 이 명령어는 성공하더라도 출력을 표시하지 않습니다. 자세한 응답을 출력하려면 명령어에 --format=json 플래그를 추가합니다.

예를 들어 다음 명령어는 policy.json이라는 파일을 사용하여 my-project 프로젝트에 대해 my-deny-policy라는 거부 정책을 만듭니다.

gcloud iam policies create my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies \
    --policy-file=policy.json

Terraform

Terraform 구성을 적용하거나 삭제하는 방법은 기본 Terraform 명령어를 참조하세요. 자세한 내용은 Terraform 제공업체 참고 문서를 확인하세요.

data "google_project" "default" {
}

# Create a service account
resource "google_service_account" "default" {
  display_name = "IAM Deny Example - Service Account"
  account_id   = "example-sa"
  project      = data.google_project.default.project_id
}

# Create an IAM deny policy that denies a permission for the service account
resource "google_iam_deny_policy" "default" {
  provider     = google-beta
  parent       = urlencode("cloudresourcemanager.googleapis.com/projects/${data.google_project.default.project_id}")
  name         = "my-deny-policy"
  display_name = "My deny policy."
  rules {
    deny_rule {
      denied_principals  = ["principal://iam.googleapis.com/projects/-/serviceAccounts/${google_service_account.default.email}"]
      denied_permissions = ["iam.googleapis.com/roles.create"]
    }
  }
}

Go

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Go API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	iampb "google.golang.org/genproto/googleapis/iam/v2"

	"google.golang.org/genproto/googleapis/type/expr"
)

// createDenyPolicy creates a deny policy.
func createDenyPolicy(w io.Writer, projectID, policyID string) error {
	// You can add deny policies to organizations, folders, and projects.
	// Each of these resources can have up to 5 deny policies.
	// Deny policies contain deny rules, which specify the following:
	// 1. The permissions to deny and/or exempt.
	// 2. The principals that are denied, or exempted from denial.
	// 3. An optional condition on when to enforce the deny rules.

	// projectID := "your_project_id"
	// policyID := "your_policy_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	denyRule := &iampb.DenyRule{
		// Add one or more principals who should be denied the permissions specified in this rule.
		// For more information on allowed values,
		// see: https://cloud.google.com/iam/help/deny/principal-identifiers
		DeniedPrincipals: []string{"principalSet://goog/public:all"},
		// Optionally, set the principals who should be exempted from the
		// list of denied principals. For example, if you want to deny certain permissions
		// to a group but exempt a few principals, then add those here.
		// ExceptionPrincipals: []string{"principalSet://goog/group/project-admins@example.com"},
		//
		// Set the permissions to deny.
		// The permission value is of the format: service_fqdn/resource.action
		// For the list of supported permissions,
		// see: https://cloud.google.com/iam/help/deny/supported-permissions
		DeniedPermissions: []string{"cloudresourcemanager.googleapis.com/projects.delete"},
		// Optionally, add the permissions to be exempted from this rule.
		// Meaning, the deny rule will not be applicable to these permissions.
		// ExceptionPermissions: []string{"cloudresourcemanager.googleapis.com/projects.create"},
		//
		// Set the condition which will enforce the deny rule.
		// If this condition is true, the deny rule will be applicable.
		// Else, the rule will not be enforced.
		// The expression uses Common Expression Language syntax (CEL).
		// Here we block access based on tags.
		//
		// Here, we create a deny rule that denies the
		// cloudresourcemanager.googleapis.com/projects.delete permission
		// to everyone except project-admins@example.com for resources that are tagged test.
		// A tag is a key-value pair that can be attached to an organization, folder, or project.
		// For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
		DenialCondition: &expr.Expr{
			Expression: "!resource.matchTag('12345678/env', 'test')",
		},
	}

	// Add the deny rule and a description for it.
	policyRule := &iampb.PolicyRule{
		Description: "block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value test",
		Kind: &iampb.PolicyRule_DenyRule{
			DenyRule: denyRule,
		},
	}

	policy := &iampb.Policy{
		DisplayName: "Restrict project deletion access",
		Rules:       [](*iampb.PolicyRule){policyRule},
	}

	req := &iampb.CreatePolicyRequest{
		// Construct the full path of the resource's deny policies.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies"
		Parent:   fmt.Sprintf("policies/%s/denypolicies", attachmentPoint),
		Policy:   policy,
		PolicyId: policyID,
	}
	op, err := policiesClient.CreatePolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create policy: %w", err)
	}

	policy, err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Policy %s created\n", policy.GetName())

	return nil
}

Java

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Java API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.


import com.google.iam.v2.CreatePolicyRequest;
import com.google.iam.v2.DenyRule;
import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import com.google.iam.v2.PolicyRule;
import com.google.longrunning.Operation;
import com.google.type.Expr;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateDenyPolicy {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the id of the Deny policy you want to create.
    String policyId = "deny-policy-id";

    createDenyPolicy(projectId, policyId);
  }

  // Create a deny policy.
  // You can add deny policies to organizations, folders, and projects.
  // Each of these resources can have up to 5 deny policies.
  //
  // Deny policies contain deny rules, which specify the following:
  // 1. The permissions to deny and/or exempt.
  // 2. The principals that are denied, or exempted from denial.
  // 3. An optional condition on when to enforce the deny rules.
  public static void createDenyPolicy(String projectId, String policyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    try (PoliciesClient policiesClient = PoliciesClient.create()) {
      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies", attachmentPoint);

      DenyRule denyRule =
          DenyRule.newBuilder()
              // Add one or more principals who should be denied the permissions specified in this
              // rule.
              // For more information on allowed values, see:
              // https://cloud.google.com/iam/docs/principal-identifiers
              .addDeniedPrincipals("principalSet://goog/public:all")

              // Optionally, set the principals who should be exempted from the
              // list of denied principals. For example, if you want to deny certain permissions
              // to a group but exempt a few principals, then add those here.
              // .addExceptionPrincipals(
              //     "principalSet://goog/group/project-admins@example.com")

              // Set the permissions to deny.
              // The permission value is of the format: service_fqdn/resource.action
              // For the list of supported permissions, see:
              // https://cloud.google.com/iam/help/deny/supported-permissions
              .addDeniedPermissions("cloudresourcemanager.googleapis.com/projects.delete")

              // Optionally, add the permissions to be exempted from this rule.
              // Meaning, the deny rule will not be applicable to these permissions.
              // .addExceptionPermissions("cloudresourcemanager.googleapis.com/projects.create")

              // Set the condition which will enforce the deny rule. If this condition is true,
              // the deny rule will be applicable. Else, the rule will not be enforced.
              .setDenialCondition(
                  Expr.newBuilder()
                      // The expression uses Common Expression Language syntax (CEL).
                      // Here we block access based on tags.
                      //
                      // A tag is a key-value pair that can be attached to an organization, folder,
                      // or project. You can use deny policies to deny permissions based on tags
                      // without adding an IAM Condition to every role grant.
                      // For example, imagine that you tag all of your projects as dev, test, or
                      // prod. You want only members of project-admins@example.com to be able to
                      // perform operations on projects that are tagged prod.
                      // To solve this problem, you create a deny rule that denies the
                      // cloudresourcemanager.googleapis.com/projects.delete permission to everyone
                      // except project-admins@example.com for resources that are tagged test.
                      .setExpression("!resource.matchTag('12345678/env', 'test')")
                      .setTitle("Only for test projects")
                      .build())
              .build();

      // Add the deny rule and a description for it.
      Policy policy =
          Policy.newBuilder()
              // Set the deny rule.
              .addRules(
                  PolicyRule.newBuilder()
                      // Set a description for the rule.
                      .setDescription(
                          "block all principals from deleting projects, unless the principal"
                              + " is a member of project-admins@example.com and the project"
                              + " being deleted has a tag with the value test")
                      .setDenyRule(denyRule)
                      .build())
              .build();

      // Set the policy resource path, policy rules and a unique ID for the policy.
      CreatePolicyRequest createPolicyRequest =
          CreatePolicyRequest.newBuilder()
              .setParent(policyParent)
              .setPolicy(policy)
              .setPolicyId(policyId)
              .build();

      // Build the create policy request.
      Operation operation =
          policiesClient
              .createPolicyCallable()
              .futureCall(createPolicyRequest)
              .get(3, TimeUnit.MINUTES);

      // Wait for the operation to complete.
      if (operation.hasError()) {
        System.out.println("Error in creating the policy " + operation.getError());
        return;
      }

      // Retrieve the policy name.
      Policy response = policiesClient.getPolicy(String.format("%s/%s", policyParent, policyId));
      String policyName = response.getName();
      System.out.println(
          "Created the deny policy: " + policyName.substring(policyName.lastIndexOf("/") + 1));
    }
  }
}

Node.js

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Node.js API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

const denyRule = {
  // Add one or more principals who should be denied the permissions specified in this rule.
  // For more information on allowed values, see: https://cloud.google.com/iam/help/deny/principal-identifiers
  deniedPrincipals: ['principalSet://goog/public:all'],
  // Optionally, set the principals who should be exempted from the
  // list of denied principals. For example, if you want to deny certain permissions
  // to a group but exempt a few principals, then add those here.
  // exceptionPrincipals: ['principalSet://goog/group/project-admins@example.com'],
  // Set the permissions to deny.
  // The permission value is of the format: service_fqdn/resource.action
  // For the list of supported permissions, see: https://cloud.google.com/iam/help/deny/supported-permissions
  deniedPermissions: ['cloudresourcemanager.googleapis.com/projects.delete'],
  // Optionally, add the permissions to be exempted from this rule.
  // Meaning, the deny rule will not be applicable to these permissions.
  // exceptionPermissions: ['cloudresourcemanager.googleapis.com/projects.create']
  //
  // Set the condition which will enforce the deny rule.
  // If this condition is true, the deny rule will be applicable. Else, the rule will not be enforced.
  // The expression uses Common Expression Language syntax (CEL).
  // Here we block access based on tags.
  //
  // Here, we create a deny rule that denies the cloudresourcemanager.googleapis.com/projects.delete permission to everyone except project-admins@example.com for resources that are tagged test.
  // A tag is a key-value pair that can be attached to an organization, folder, or project.
  // For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
  denialCondition: {
    expression: '!resource.matchTag("12345678/env", "test")',
  },
};

async function createDenyPolicy() {
  const request = {
    parent: `policies/${attachmentPoint}/denypolicies`,
    policy: {
      displayName: 'Restrict project deletion access',
      rules: [
        {
          description:
            'block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value test',
          denyRule,
        },
      ],
    },
    policyId,
  };

  const [operation] = await iamClient.createPolicy(request);
  const [policy] = await operation.promise();

  console.log(`Created the deny policy: ${policy.name}`);
}

createDenyPolicy();

Python

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Python API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.



def create_deny_policy(project_id: str, policy_id: str) -> None:
    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    """
      Create a deny policy.
      You can add deny policies to organizations, folders, and projects.
      Each of these resources can have up to 5 deny policies.

      Deny policies contain deny rules, which specify the following:
      1. The permissions to deny and/or exempt.
      2. The principals that are denied, or exempted from denial.
      3. An optional condition on when to enforce the deny rules.

      Params:
      project_id: ID or number of the Google Cloud project you want to use.
      policy_id: Specify the ID of the deny policy you want to create.
    """
    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    deny_rule = types.DenyRule()
    # Add one or more principals who should be denied the permissions specified in this rule.
    # For more information on allowed values, see: https://cloud.google.com/iam/help/deny/principal-identifiers
    deny_rule.denied_principals = ["principalSet://goog/public:all"]

    # Optionally, set the principals who should be exempted from the
    # list of denied principals. For example, if you want to deny certain permissions
    # to a group but exempt a few principals, then add those here.
    # deny_rule.exception_principals = ["principalSet://goog/group/project-admins@example.com"]

    # Set the permissions to deny.
    # The permission value is of the format: service_fqdn/resource.action
    # For the list of supported permissions, see: https://cloud.google.com/iam/help/deny/supported-permissions
    deny_rule.denied_permissions = [
        "cloudresourcemanager.googleapis.com/projects.delete"
    ]

    # Optionally, add the permissions to be exempted from this rule.
    # Meaning, the deny rule will not be applicable to these permissions.
    # deny_rule.exception_permissions = ["cloudresourcemanager.googleapis.com/projects.create"]

    # Set the condition which will enforce the deny rule.
    # If this condition is true, the deny rule will be applicable. Else, the rule will not be enforced.
    # The expression uses Common Expression Language syntax (CEL).
    # Here we block access based on tags.
    #
    # Here, we create a deny rule that denies the cloudresourcemanager.googleapis.com/projects.delete permission to everyone except project-admins@example.com for resources that are tagged test.
    # A tag is a key-value pair that can be attached to an organization, folder, or project.
    # For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
    deny_rule.denial_condition = {
        "expression": "!resource.matchTag('12345678/env', 'test')"
    }

    # Add the deny rule and a description for it.
    policy_rule = types.PolicyRule()
    policy_rule.description = "block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value test"
    policy_rule.deny_rule = deny_rule

    policy = types.Policy()
    policy.display_name = "Restrict project deletion access"
    policy.rules = [policy_rule]

    # Set the policy resource path, policy rules and a unique ID for the policy.
    request = types.CreatePolicyRequest()
    # Construct the full path of the resource's deny policies.
    # Its format is: "policies/{attachmentPoint}/denypolicies"
    request.parent = f"policies/{attachment_point}/denypolicies"
    request.policy = policy
    request.policy_id = policy_id

    # Build the create policy request and wait for the operation to complete.
    result = policies_client.create_policy(request=request).result()
    print(f"Created the deny policy: {result.name.rsplit('/')[-1]}")

if __name__ == "__main__":
    import uuid

    # Your Google Cloud project ID.
    project_id = "your-google-cloud-project-id"
    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    # Test the policy lifecycle.
    create_deny_policy(project_id, policy_id)

REST

policies.createPolicy 메서드는 리소스에 대해 거부 정책을 만듭니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • ENCODED_ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 URL 인코딩 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

  • POLICY_ID: 거부 정책의 식별자입니다.
  • POLICY_NAME: 거부 정책의 표시 이름입니다.
  • DENY_RULE_1, DENY_RULE_2, ...DENY_RULE_N: 정책의 거부 규칙입니다. 각 거부 규칙에는 다음 필드가 포함될 수 있습니다.

    • deniedPermissions: 지정된 주 구성원이 사용할 수 없는 권한 목록입니다. 권한은 거부 정책에서 지원되어야 합니다.

      경우에 따라 권한 그룹을 사용하여 권한 집합을 거부할 수도 있습니다. 자세한 내용은 권한 그룹을 참조하세요.

    • deniedPrincipals: 지정된 권한을 사용할 수 없는 주 구성원의 목록입니다. 주 구성원 식별자에 대해 v2 API 형식을 사용합니다.
    • exceptionPrincipals: (선택사항) 주 구성원이 deniedPrincipals에 포함된 경우에도 지정된 권한을 사용할 수 있는 주 구성원 목록입니다. 예를 들어 이 필드를 사용하여 거부된 그룹에 속하는 특정 사용자에 대해 예외를 설정할 수 있습니다. 주 구성원 식별자에 대해 v2 API 형식을 사용합니다.
    • denialCondition: (선택사항) 주 구성원이 권한을 사용할 수 없는 경우를 지정하는 조건 표현식입니다. 다음 필드가 포함됩니다.

    거부 규칙 예시는 일반 사용 사례를 참조하세요.

HTTP 메서드 및 URL:

POST https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies?policyId=POLICY_ID

JSON 요청 본문:

{
  "displayName": "POLICY_NAME",
  "rules": [
    {
      "denyRule": DENY_RULE_1
    },
    {
      "denyRule": DENY_RULE_2
    },

    {
      "denyRule": DENY_RULE_N
    }
  ]
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/89cb3e508bf1ff01",
  "metadata": {
    "@type": "type.googleapis.com/google.iam.v2.PolicyOperationMetadata",
    "createTime": "2022-06-28T19:06:12.455151Z"
  },
  "response": {
    "@type": "type.googleapis.com/google.iam.v2.Policy",
    "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
    "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
    "kind": "DenyPolicy",
    "displayName": "My deny policy.",
    "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
    "createTime": "2022-06-28T19:06:12.455151Z",
    "updateTime": "2022-06-28T22:26:21.968687Z"
    "rules": [
      {
        "denyRule": {
          "deniedPrincipals": [
            "principal://goog/subject/lucian@example.com"
          ],
          "deniedPermissions": [
            "iam.googleapis.com/roles.create"
          ]
        }
      }
    ]
  }
}

응답은 장기 실행 작업을 식별합니다. 장기 실행 작업의 상태를 모니터링하여 완료되는 시간을 찾아낼 수 있습니다. 자세한 내용은 이 페이지에서 장기 실행 작업의 상태 확인을 참조하세요.

거부 정책 나열

리소스는 거부 정책을 여러 개 포함할 수 있습니다. 리소스에 연결된 모든 거부 정책을 나열한 후 각 거부 정책을 확인하여 각 정책의 거부 규칙을 볼 수 있습니다.

gcloud

리소스의 거부 정책을 나열하려면 gcloud iam policies list 명령어를 실행합니다.

gcloud iam policies list \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --format=json

다음 값을 제공합니다.

  • ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

예를 들어 다음 명령어는 해당 숫자 ID가 123456789012인 조직에 연결된 거부 정책을 나열합니다.

gcloud iam policies list \
    --attachment-point=cloudresourcemanager.googleapis.com/organizations/123456789012 \
    --kind=denypolicies \
    --format=json

Go

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Go API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	"google.golang.org/api/iterator"
	iampb "google.golang.org/genproto/googleapis/iam/v2"
)

// listDenyPolicies lists all the deny policies that are attached to a resource.
// A resource can have up to 5 deny policies.
func listDenyPolicies(w io.Writer, projectID string) error {
	// projectID := "your_project_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	req := &iampb.ListPoliciesRequest{
		// Construct the full path of the resource's deny policies.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies"
		Parent: fmt.Sprintf("policies/%s/denypolicies", attachmentPoint),
	}
	it := policiesClient.ListPolicies(ctx, req)
	fmt.Fprintf(w, "Policies found in project %s:\n", projectID)

	for {
		policy, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "- %s\n", policy.GetName())
	}
	return nil
}

Java

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Java API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.


import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class ListDenyPolicies {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    listDenyPolicies(projectId);
  }

  // List all the deny policies that are attached to a resource.
  // A resource can have up to 5 deny policies.
  public static void listDenyPolicies(String projectId) throws IOException {
    // Initialize the Policies client.
    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies"
      String policyParent = String.format("policies/%s/denypolicies", attachmentPoint);

      // Create a list request and iterate over the returned policies.
      for (Policy policy : policiesClient.listPolicies(policyParent).iterateAll()) {
        System.out.println(policy.getName());
      }
      System.out.println("Listed all deny policies");
    }
  }
}

Node.js

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Node.js API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

async function listDenyPolicies() {
  const request = {
    parent: `policies/${attachmentPoint}/denypolicies`,
  };

  const policies = await iamClient.listPoliciesAsync(request);
  for await (const policy of policies) {
    console.log(`- ${policy.name}`);
  }
}

listDenyPolicies();

Python

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Python API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

def list_deny_policy(project_id: str) -> None:
    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    """
    List all the deny policies that are attached to a resource.
    A resource can have up to 5 deny policies.

    project_id: ID or number of the Google Cloud project you want to use.
    """
    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    request = types.ListPoliciesRequest()
    # Construct the full path of the resource's deny policies.
    # Its format is: "policies/{attachmentPoint}/denypolicies"
    request.parent = f"policies/{attachment_point}/denypolicies"

    # Create a list request and iterate over the returned policies.
    policies = policies_client.list_policies(request=request)

    for policy in policies:
        print(policy.name)
    print("Listed all deny policies")

if __name__ == "__main__":
    import uuid

    # Your Google Cloud project ID.
    project_id = "your-google-cloud-project-id"
    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    list_deny_policy(project_id)

REST

policies.listPolicies 메서드는 리소스에 대해 거부 정책을 나열합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • ENCODED_ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 URL 인코딩 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

HTTP 메서드 및 URL:

GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "policies": [
    {
      "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1067607927478/denypolicies/test-policy",
      "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
      "kind": "DenyPolicy",
      "displayName": "My deny policy.",
      "createTime": "2022-06-28T19:06:12.455151Z",
      "updateTime": "2022-06-28T22:26:21.968687Z"
    },
    {
      "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1067607927478/denypolicies/test-policy-2",
      "uid": "8465d710-ea20-0a08-d92c-b2a3ebf766ab",
      "kind": "DenyPolicy",
      "displayName": "My second deny policy.",
      "createTime": "2022-06-05T19:21:53.595455Z",
      "updateTime": "2022-06-05T19:21:53.595455Z"
    },
    {
      "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1067607927478/denypolicies/test-policy-3",
      "uid": "ee9f7c2f-7e8c-b05c-d4e5-e03bfb2954e0",
      "kind": "DenyPolicy",
      "displayName": "My third deny policy.",
      "createTime": "2022-06-05T19:22:26.770543Z",
      "updateTime": "2022-06-05T19:22:26.770543Z"
    }
  ]
}

거부 정책 보기

거부된 권한, 권한을 사용할 수 없는 주 구성원 등 거부 정책을 확인하여 포함된 거부 규칙을 볼 수 있습니다.

gcloud

리소스의 거부 정책을 가져오려면 gcloud iam policies get 명령어를 실행합니다.

gcloud iam policies get POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --format=json

다음 값을 제공합니다.

  • POLICY_ID: 거부 정책의 식별자입니다.

  • ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

예를 들어 다음 명령어는 my-project 프로젝트에 대해 my-deny-policy라는 거부 정책을 가져오고 이를 policy.json이라는 파일에 저장합니다.

gcloud iam policies get my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies \
    --format=json \
    > ./policy.json

Go

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Go API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	iampb "google.golang.org/genproto/googleapis/iam/v2"
)

// getDenyPolicy retrieves the deny policy given the project ID and policy ID.
func getDenyPolicy(w io.Writer, projectID, policyID string) error {
	// projectID := "your_project_id"
	// policyID := "your_policy_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	req := &iampb.GetPolicyRequest{
		// Construct the full path of the policy.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies/POLICY_ID"
		Name: fmt.Sprintf("policies/%s/denypolicies/%s", attachmentPoint, policyID),
	}
	policy, err := policiesClient.GetPolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to get policy: %w", err)
	}

	fmt.Fprintf(w, "Policy %s retrieved\n", policy.GetName())

	return nil
}

Java

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Java API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.


import com.google.iam.v2.GetPolicyRequest;
import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class GetDenyPolicy {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the ID of the deny policy you want to retrieve.
    String policyId = "deny-policy-id";

    getDenyPolicy(projectId, policyId);
  }

  // Retrieve the deny policy given the project ID and policy ID.
  public static void getDenyPolicy(String projectId, String policyId) throws IOException {
    // Create the IAM Policies client.
    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

      // Specify the policyParent and execute the GetPolicy request.
      GetPolicyRequest getPolicyRequest =
          GetPolicyRequest.newBuilder().setName(policyParent).build();

      Policy policy = policiesClient.getPolicy(getPolicyRequest);
      System.out.printf("Retrieved the deny policy: %s : %s%n", policyId, policy);
    }
  }
}

Node.js

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Node.js API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

async function getDenyPolicy() {
  const request = {
    name: `policies/${attachmentPoint}/denypolicies/${policyId}`,
  };

  const [policy] = await iamClient.getPolicy(request);

  console.log(`Retrieved the deny policy: ${policy.name}`);
}

getDenyPolicy();

Python

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Python API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

from google.cloud import iam_v2
from google.cloud.iam_v2 import Policy, types

def get_deny_policy(project_id: str, policy_id: str) -> Policy:
    """
    Retrieve the deny policy given the project ID and policy ID.

    project_id: ID or number of the Google Cloud project you want to use.
    policy_id: The ID of the deny policy you want to retrieve.
    """
    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    request = types.GetPolicyRequest()
    # Construct the full path of the policy.
    # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
    request.name = f"policies/{attachment_point}/denypolicies/{policy_id}"

    # Execute the GetPolicy request.
    policy = policies_client.get_policy(request=request)
    print(f"Retrieved the deny policy: {policy_id} : {policy}")
    return policy

if __name__ == "__main__":
    import uuid

    # Your Google Cloud project ID.
    project_id = "your-google-cloud-project-id"
    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    policy = get_deny_policy(project_id, policy_id)

REST

policies.get 메서드는 리소스에 대해 거부 정책을 가져옵니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • ENCODED_ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 URL 인코딩 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

  • POLICY_ID: 거부 정책의 식별자입니다.

HTTP 메서드 및 URL:

GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
  "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
  "kind": "DenyPolicy",
  "displayName": "My deny policy.",
  "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
  "createTime": "2022-06-05T19:22:26.770543Z",
  "updateTime": "2022-06-05T19:22:26.770543Z",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": [
          "principal://goog/subject/lucian@example.com"
        ],
        "deniedPermissions": [
          "iam.googleapis.com/roles.create"
        ]
      }
    }
  ]
}

거부 정책 업데이트

거부 정책을 만든 후에는 여기에 포함된 거부 규칙은 물론 해당 표시 이름을 업데이트할 수 있습니다.

거부 정책을 업데이트하려면 읽기-수정-쓰기 패턴을 사용합니다.

  1. 정책의 현재 버전을 읽습니다.
  2. 필요에 따라 정책의 정보를 수정합니다.
  3. 업데이트된 정책을 작성합니다.

거부 정책 읽기

gcloud

리소스의 거부 정책을 가져오려면 gcloud iam policies get 명령어를 실행합니다.

gcloud iam policies get POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --format=json

다음 값을 제공합니다.

  • POLICY_ID: 거부 정책의 식별자입니다.

  • ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

예를 들어 다음 명령어는 my-project 프로젝트에 대해 my-deny-policy라는 거부 정책을 가져오고 이를 policy.json이라는 파일에 저장합니다.

gcloud iam policies get my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies \
    --format=json \
    > ./policy.json

Go

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Go API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	iampb "google.golang.org/genproto/googleapis/iam/v2"
)

// getDenyPolicy retrieves the deny policy given the project ID and policy ID.
func getDenyPolicy(w io.Writer, projectID, policyID string) error {
	// projectID := "your_project_id"
	// policyID := "your_policy_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	req := &iampb.GetPolicyRequest{
		// Construct the full path of the policy.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies/POLICY_ID"
		Name: fmt.Sprintf("policies/%s/denypolicies/%s", attachmentPoint, policyID),
	}
	policy, err := policiesClient.GetPolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to get policy: %w", err)
	}

	fmt.Fprintf(w, "Policy %s retrieved\n", policy.GetName())

	return nil
}

Java

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Java API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.


import com.google.iam.v2.GetPolicyRequest;
import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class GetDenyPolicy {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the ID of the deny policy you want to retrieve.
    String policyId = "deny-policy-id";

    getDenyPolicy(projectId, policyId);
  }

  // Retrieve the deny policy given the project ID and policy ID.
  public static void getDenyPolicy(String projectId, String policyId) throws IOException {
    // Create the IAM Policies client.
    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

      // Specify the policyParent and execute the GetPolicy request.
      GetPolicyRequest getPolicyRequest =
          GetPolicyRequest.newBuilder().setName(policyParent).build();

      Policy policy = policiesClient.getPolicy(getPolicyRequest);
      System.out.printf("Retrieved the deny policy: %s : %s%n", policyId, policy);
    }
  }
}

Node.js

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Node.js API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

async function getDenyPolicy() {
  const request = {
    name: `policies/${attachmentPoint}/denypolicies/${policyId}`,
  };

  const [policy] = await iamClient.getPolicy(request);

  console.log(`Retrieved the deny policy: ${policy.name}`);
}

getDenyPolicy();

Python

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Python API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

from google.cloud import iam_v2
from google.cloud.iam_v2 import Policy, types

def get_deny_policy(project_id: str, policy_id: str) -> Policy:
    """
    Retrieve the deny policy given the project ID and policy ID.

    project_id: ID or number of the Google Cloud project you want to use.
    policy_id: The ID of the deny policy you want to retrieve.
    """
    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    request = types.GetPolicyRequest()
    # Construct the full path of the policy.
    # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
    request.name = f"policies/{attachment_point}/denypolicies/{policy_id}"

    # Execute the GetPolicy request.
    policy = policies_client.get_policy(request=request)
    print(f"Retrieved the deny policy: {policy_id} : {policy}")
    return policy

if __name__ == "__main__":
    import uuid

    # Your Google Cloud project ID.
    project_id = "your-google-cloud-project-id"
    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    policy = get_deny_policy(project_id, policy_id)

REST

policies.get 메서드는 리소스에 대해 거부 정책을 가져옵니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • ENCODED_ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 URL 인코딩 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

  • POLICY_ID: 거부 정책의 식별자입니다.

HTTP 메서드 및 URL:

GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
  "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
  "kind": "DenyPolicy",
  "displayName": "My deny policy.",
  "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
  "createTime": "2022-06-05T19:22:26.770543Z",
  "updateTime": "2022-06-05T19:22:26.770543Z",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": [
          "principal://goog/subject/lucian@example.com"
        ],
        "deniedPermissions": [
          "iam.googleapis.com/roles.create"
        ]
      }
    }
  ]
}

거부 정책 수정

거부 정책을 수정하려면 IAM에서 이전에 읽은 정책의 사본을 변경합니다. 표시 이름을 업데이트하거나 거부 규칙을 추가, 변경, 삭제할 수 있습니다. 업데이트된 정책을 작성할 때까지는 변경사항이 적용되지 않습니다.

예를 들어 기존 거부 규칙에 권한을 추가할 수 있습니다.

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
  "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
  "kind": "DenyPolicy",
  "displayName": "My deny policy.",
  "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
  "createTime": "2021-10-05T19:22:26.770543Z",
  "updateTime": "2021-10-05T19:22:26.770543Z",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": [
          "principal://goog/subject/lucian@example.com"
        ],
        "deniedPermissions": [
          "iam.googleapis.com/roles.create",
          "iam.googleapis.com/roles.delete"
        ]
      }
    }
  ]
}

업데이트된 거부 정책 작성

로컬로 거부 정책을 수정한 후에는 업데이트된 거부 정책을 IAM에 작성해야 합니다.

각 거부 정책에는 정책 버전을 식별하는 etag 필드가 포함됩니다. etag는 정책을 업데이트할 때마다 변경됩니다. 업데이트된 정책을 작성할 때 요청의 etag는 IAM에 저장된 현재 etag와 일치해야 합니다. 값이 일치하지 않으면 요청이 실패합니다. 이 기능은 동시 변경사항이 서로 덮어쓰지 않도록 방지하는 데 도움이 됩니다.

gcloud

리소스의 거부 정책을 업데이트하려면 gcloud iam policies update 명령어를 실행합니다.

gcloud iam policies update POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --policy-file=POLICY_FILE

다음 값을 제공합니다.

  • POLICY_ID: 거부 정책의 식별자입니다.

  • ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

  • POLICY_FILE: 거부 정책을 포함하는 JSON 파일의 파일 경로입니다.

기본적으로 이 명령어는 성공하더라도 출력을 표시하지 않습니다. 자세한 응답을 출력하려면 명령어에 --format=json 플래그를 추가합니다.

예를 들어 다음 명령어는 policy.json이라는 파일을 사용하여 my-project 프로젝트에 대해 my-deny-policy라는 거부 정책을 업데이트합니다.

gcloud iam policies update my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies \
    --policy-file=policy.json

Go

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Go API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"

	iampb "google.golang.org/genproto/googleapis/iam/v2"
	"google.golang.org/genproto/googleapis/type/expr"
)

// updateDenyPolicy updates the deny rules and/ or its display name after policy creation.
func updateDenyPolicy(w io.Writer, projectID, policyID, etag string) error {
	// projectID := "your_project_id"
	// policyID := "your_policy_id"
	// etag := "your_etag"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	denyRule := &iampb.DenyRule{
		// Add one or more principals who should be denied the permissions specified in this rule.
		// For more information on allowed values,
		// see: https://cloud.google.com/iam/help/deny/principal-identifiers
		DeniedPrincipals: []string{"principalSet://goog/public:all"},
		// Optionally, set the principals who should be exempted from the
		// list of denied principals. For example, if you want to deny certain permissions
		// to a group but exempt a few principals, then add those here.
		// ExceptionPrincipals: []string{"principalSet://goog/group/project-admins@example.com"},
		//
		// Set the permissions to deny.
		// The permission value is of the format: service_fqdn/resource.action
		// For the list of supported permissions,
		// see: https://cloud.google.com/iam/help/deny/supported-permissions
		DeniedPermissions: []string{"cloudresourcemanager.googleapis.com/projects.delete"},
		// Optionally, add the permissions to be exempted from this rule.
		// Meaning, the deny rule will not be applicable to these permissions.
		// ExceptionPermissions: []string{"cloudresourcemanager.googleapis.com/projects.create"},
		//
		// Set the condition which will enforce the deny rule.
		// If this condition is true, the deny rule will be applicable.
		// Else, the rule will not be enforced.
		// The expression uses Common Expression Language syntax (CEL).
		// Here we block access based on tags.
		//
		// Here, we create a deny rule that denies the
		// cloudresourcemanager.googleapis.com/projects.delete permission
		// to everyone except project-admins@example.com for resources that are tagged prod.
		// A tag is a key-value pair that can be attached to an organization, folder, or project.
		// For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
		DenialCondition: &expr.Expr{
			Expression: "!resource.matchTag('12345678/env', 'prod')",
		},
	}

	// Set the rule description and deny rule to update.
	policyRule := &iampb.PolicyRule{
		Description: "block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value prod",
		Kind: &iampb.PolicyRule_DenyRule{
			DenyRule: denyRule,
		},
	}

	// Set the policy resource path, version (etag) and the updated deny rules.
	policy := &iampb.Policy{
		// Construct the full path of the policy.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies/POLICY_ID"
		Name:  fmt.Sprintf("policies/%s/denypolicies/%s", attachmentPoint, policyID),
		Etag:  etag,
		Rules: [](*iampb.PolicyRule){policyRule},
	}

	// Create the update policy request.
	req := &iampb.UpdatePolicyRequest{
		Policy: policy,
	}
	op, err := policiesClient.UpdatePolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to update policy: %w", err)
	}

	policy, err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Policy %s updated\n", policy.GetName())

	return nil
}

Java

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Java API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.


import com.google.iam.v2.DenyRule;
import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import com.google.iam.v2.PolicyRule;
import com.google.iam.v2.UpdatePolicyRequest;
import com.google.longrunning.Operation;
import com.google.type.Expr;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UpdateDenyPolicy {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.

    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the ID of the Deny policy you want to retrieve.
    String policyId = "deny-policy-id";

    // Etag field that identifies the policy version. The etag changes each time
    // you update the policy. Get the etag of an existing policy by performing a GetPolicy request.
    String etag = "policy_etag";

    updateDenyPolicy(projectId, policyId, etag);
  }

  // Update the deny rules and/ or its display name after policy creation.
  public static void updateDenyPolicy(String projectId, String policyId, String etag)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached to.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

      DenyRule denyRule =
          DenyRule.newBuilder()
              // Add one or more principals who should be denied the permissions specified in this
              // rule.
              // For more information on allowed values, see:
              // https://cloud.google.com/iam/docs/principal-identifiers
              .addDeniedPrincipals("principalSet://goog/public:all")

              // Optionally, set the principals who should be exempted from the list of principals
              // added in "DeniedPrincipals".
              // Example, if you want to deny certain permissions to a group but exempt a few
              // principals, then add those here.
              // .addExceptionPrincipals(
              //     "principalSet://goog/group/project-admins@example.com")

              // Set the permissions to deny.
              // The permission value is of the format: service_fqdn/resource.action
              // For the list of supported permissions, see:
              // https://cloud.google.com/iam/help/deny/supported-permissions
              .addDeniedPermissions("cloudresourcemanager.googleapis.com/projects.delete")

              // Add the permissions to be exempted from this rule.
              // Meaning, the deny rule will not be applicable to these permissions.
              // .addExceptionPermissions("cloudresourcemanager.googleapis.com/projects.get")

              // Set the condition which will enforce the deny rule.
              // If this condition is true, the deny rule will be applicable. Else, the rule will
              // not be enforced.
              .setDenialCondition(
                  Expr.newBuilder()
                      // The expression uses Common Expression Language syntax (CEL). Here we block
                      // access based on tags.
                      //
                      // A tag is a key-value pair that can be attached to an organization, folder,
                      // or project. You can use deny policies to deny permissions based on tags
                      // without adding an IAM Condition to every role grant.
                      // For example, imagine that you tag all of your projects as dev, test, or
                      // prod. You want only members of project-admins@example.com to be able to
                      // perform operations on projects that are tagged prod.
                      // To solve this problem, you create a deny rule that denies the
                      // cloudresourcemanager.googleapis.com/projects.delete permission to everyone
                      // except project-admins@example.com for resources that are tagged prod.
                      .setExpression("!resource.matchTag('12345678/env', 'prod')")
                      .setTitle("Only for prod projects")
                      .build())
              .build();

      // Set the policy resource path, version (etag) and the updated deny rules.
      Policy policy =
          Policy.newBuilder()
              .setName(policyParent)
              .setEtag(etag)
              .addRules(
                  PolicyRule.newBuilder()
                      // Set the rule description to update.
                      .setDescription(
                          "Block all principals from deleting projects, unless the principal"
                              + " is a member of project-admins@example.com and the project"
                              + "being deleted has a tag with the value prod")
                      // Set the deny rule to update.
                      .setDenyRule(denyRule)
                      .build())
              .build();

      // Create the update policy request.
      UpdatePolicyRequest updatePolicyRequest =
          UpdatePolicyRequest.newBuilder().setPolicy(policy).build();

      // Wait for the operation to complete.
      Operation operation =
          policiesClient
              .updatePolicyCallable()
              .futureCall(updatePolicyRequest)
              .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Error in updating the policy " + operation.getError());
        return;
      }

      System.out.println("Updated the deny policy: " + policyId);
    }
  }
}

Node.js

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Node.js API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';
// const etag = 'YOUR_ETAG';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

const denyRule = {
  // Add one or more principals who should be denied the permissions specified in this rule.
  // For more information on allowed values, see: https://cloud.google.com/iam/help/deny/principal-identifiers
  deniedPrincipals: ['principalSet://goog/public:all'],
  // Optionally, set the principals who should be exempted from the
  // list of denied principals. For example, if you want to deny certain permissions
  // to a group but exempt a few principals, then add those here.
  // exceptionPrincipals: ['principalSet://goog/group/project-admins@example.com'],
  // Set the permissions to deny.
  // The permission value is of the format: service_fqdn/resource.action
  // For the list of supported permissions, see: https://cloud.google.com/iam/help/deny/supported-permissions
  deniedPermissions: ['cloudresourcemanager.googleapis.com/projects.delete'],
  // Optionally, add the permissions to be exempted from this rule.
  // Meaning, the deny rule will not be applicable to these permissions.
  // exceptionPermissions: ['cloudresourcemanager.googleapis.com/projects.create']
  //
  // Set the condition which will enforce the deny rule.
  // If this condition is true, the deny rule will be applicable. Else, the rule will not be enforced.
  // The expression uses Common Expression Language syntax (CEL).
  // Here we block access based on tags.
  //
  // Here, we create a deny rule that denies the cloudresourcemanager.googleapis.com/projects.delete permission to everyone except project-admins@example.com for resources that are tagged test.
  // A tag is a key-value pair that can be attached to an organization, folder, or project.
  // For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
  denialCondition: {
    expression: '!resource.matchTag("12345678/env", "prod")',
  },
};

async function updateDenyPolicy() {
  const request = {
    policy: {
      name: `policies/${attachmentPoint}/denypolicies/${policyId}`,
      etag,
      rules: [
        {
          description:
            'block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value prod',
          denyRule,
        },
      ],
    },
    policyId,
  };

  const [operation] = await iamClient.updatePolicy(request);
  const [policy] = await operation.promise();

  console.log(`Updated the deny policy: ${policy.name}`);
}

updateDenyPolicy();

Python

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Python API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

def update_deny_policy(project_id: str, policy_id: str, etag: str) -> None:
    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    """
    Update the deny rules and/ or its display name after policy creation.

    project_id: ID or number of the Google Cloud project you want to use.

    policy_id: The ID of the deny policy you want to retrieve.

    etag: Etag field that identifies the policy version. The etag changes each time
    you update the policy. Get the etag of an existing policy by performing a GetPolicy request.
    """
    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    deny_rule = types.DenyRule()

    # Add one or more principals who should be denied the permissions specified in this rule.
    # For more information on allowed values, see: https://cloud.google.com/iam/help/deny/principal-identifiers
    deny_rule.denied_principals = ["principalSet://goog/public:all"]

    # Optionally, set the principals who should be exempted from the list of principals added in "DeniedPrincipals".
    # Example, if you want to deny certain permissions to a group but exempt a few principals, then add those here.
    # deny_rule.exception_principals = ["principalSet://goog/group/project-admins@example.com"]

    # Set the permissions to deny.
    # The permission value is of the format: service_fqdn/resource.action
    # For the list of supported permissions, see: https://cloud.google.com/iam/help/deny/supported-permissions
    deny_rule.denied_permissions = [
        "cloudresourcemanager.googleapis.com/projects.delete"
    ]

    # Add the permissions to be exempted from this rule.
    # Meaning, the deny rule will not be applicable to these permissions.
    # deny_rule.exception_permissions = ["cloudresourcemanager.googleapis.com/projects.get"]

    # Set the condition which will enforce the deny rule.
    # If this condition is true, the deny rule will be applicable. Else, the rule will not be enforced.
    #
    # The expression uses Common Expression Language syntax (CEL). Here we block access based on tags.
    #
    # Here, we create a deny rule that denies the cloudresourcemanager.googleapis.com/projects.delete permission to everyone except project-admins@example.com for resources that are tagged prod.
    # A tag is a key-value pair that can be attached to an organization, folder, or project.
    # For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
    deny_rule.denial_condition = {
        "expression": "!resource.matchTag('12345678/env', 'prod')"
    }

    # Set the rule description and deny rule to update.
    policy_rule = types.PolicyRule()
    policy_rule.description = "block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value prod"
    policy_rule.deny_rule = deny_rule

    # Set the policy resource path, version (etag) and the updated deny rules.
    policy = types.Policy()
    # Construct the full path of the policy.
    # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
    policy.name = f"policies/{attachment_point}/denypolicies/{policy_id}"
    policy.etag = etag
    policy.rules = [policy_rule]

    # Create the update policy request.
    request = types.UpdatePolicyRequest()
    request.policy = policy

    result = policies_client.update_policy(request=request).result()
    print(f"Updated the deny policy: {result.name.rsplit('/')[-1]}")

if __name__ == "__main__":
    import uuid

    # Your Google Cloud project ID.
    project_id = "your-google-cloud-project-id"
    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"
    # Get the etag by performing a Get policy request.
    etag = "etag"

    update_deny_policy(project_id, policy_id, etag)

REST

policies.update 메서드는 거부 정책을 업데이트합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • ENCODED_ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 URL 인코딩 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

  • POLICY_ID: 거부 정책의 식별자입니다.
  • POLICY: 업데이트된 거부 정책입니다.

    예를 들어 이전 단계에 표시된 정책에 권한을 추가하려면 POLICY를 다음으로 바꿉니다.

    {
      "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
      "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
      "kind": "DenyPolicy",
      "displayName": "My deny policy.",
      "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
      "createTime": "2022-06-05T19:22:26.770543Z",
      "updateTime": "2022-06-05T19:22:26.770543Z",
      "rules": [
        {
          "denyRule": {
            "deniedPrincipals": [
              "principal://goog/subject/lucian@example.com"
            ],
            "deniedPermissions": [
              "iam.googleapis.com/roles.create",
              "iam.googleapis.com/roles.delete"
            ]
          }
        }
      ]
    }

HTTP 메서드 및 URL:

PUT https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID

JSON 요청 본문:

POLICY

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/8b2d0ab2daf1ff01",
  "metadata": {
    "@type": "type.googleapis.com/google.iam.v2.PolicyOperationMetadata",
    "createTime": "2021-10-05T22:26:21.968687Z"
  },
  "response": {
    "@type": "type.googleapis.com/google.iam.v2.Policy",
    "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
    "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
    "kind": "DenyPolicy",
    "displayName": "My deny policy.",
    "etag": "MTgxNTIxNDE3NTYxNjQxODYxMTI=",
    "createTime": "2022-06-05T19:22:26.770543Z",
    "updateTime": "2022-06-05T22:26:21.968687Z",
    "rules": [
      {
        "denyRule": {
          "deniedPrincipals": [
            "principal://goog/subject/lucian@example.com"
          ],
          "deniedPermissions": [
            "iam.googleapis.com/roles.create",
            "iam.googleapis.com/roles.delete"
          ]
        }
      }
    ]
  }
}

응답은 장기 실행 작업을 식별합니다. 장기 실행 작업의 상태를 모니터링하여 완료되는 시간을 찾아낼 수 있습니다. 자세한 내용은 이 페이지에서 장기 실행 작업의 상태 확인을 참조하세요.

거부 정책 삭제

더 이상 거부 정책에 규칙을 적용하지 않으려면 거부 정책을 삭제할 수 있습니다.

선택적으로 삭제 중인 정책 버전에 대해 etag를 지정할 수 있습니다. etag를 지정할 경우 IAM에 저장된 현재 etag와 일치해야 합니다. 값이 일치하지 않으면 요청이 실패합니다. 이 기능을 사용하면 해당 정책의 업데이트된 버전 대신 의도된 정책을 삭제하는지 확인할 수 있습니다.

요청에서 etag를 생략하면 IAM이 정책을 무조건적으로 삭제합니다.

gcloud

리소스에서 거부 정책을 삭제하려면 gcloud iam policies delete 명령어를 실행합니다.

gcloud iam policies delete POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies

다음 값을 제공합니다.

  • POLICY_ID: 거부 정책의 식별자입니다.

  • ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

선택적으로 --etag=ETAG 플래그를 추가할 수 있습니다. ETAG를 거부 정책에 대해 현재 etag 값으로 바꿉니다.

기본적으로 이 명령어는 성공하더라도 출력을 표시하지 않습니다. 자세한 응답을 출력하려면 명령어에 --format=json 플래그를 추가합니다.

예를 들어 다음 명령어는 my-project 프로젝트에서 my-deny-policy라는 거부 정책을 삭제합니다.

gcloud iam policies delete my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies

Go

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Go API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"

	iampb "google.golang.org/genproto/googleapis/iam/v2"
)

// deleteDenyPolicy deletes the policy if you no longer want to enforce the rules in a deny policy.
func deleteDenyPolicy(w io.Writer, projectID, policyID string) error {
	// projectID := "your_project_id"
	// policyID := "your_policy_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	req := &iampb.DeletePolicyRequest{
		// Construct the full path of the policy.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies/POLICY_ID"
		Name: fmt.Sprintf("policies/%s/denypolicies/%s", attachmentPoint, policyID),
	}
	op, err := policiesClient.DeletePolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to delete policy: %w", err)
	}

	policy, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Policy %s deleted\n", policy.GetName())

	return nil
}

Java

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Java API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.


import com.google.iam.v2.DeletePolicyRequest;
import com.google.iam.v2.PoliciesClient;
import com.google.longrunning.Operation;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteDenyPolicy {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.

    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the ID of the deny policy you want to retrieve.
    String policyId = "deny-policy-id";

    deleteDenyPolicy(projectId, policyId);
  }

  // Delete the policy if you no longer want to enforce the rules in a deny policy.
  public static void deleteDenyPolicy(String projectId, String policyId)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

      // Create the DeletePolicy request.
      DeletePolicyRequest deletePolicyRequest =
          DeletePolicyRequest.newBuilder().setName(policyParent).build();

      // Delete the policy and wait for the operation to complete.
      Operation operation =
          policiesClient
              .deletePolicyCallable()
              .futureCall(deletePolicyRequest)
              .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Error in deleting the policy " + operation.getError());
        return;
      }

      System.out.println("Deleted the deny policy: " + policyId);
    }
  }
}

Node.js

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Node.js API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

async function deleteDenyPolicy() {
  const request = {
    name: `policies/${attachmentPoint}/denypolicies/${policyId}`,
  };

  const [operation] = await iamClient.deletePolicy(request);
  const [policy] = await operation.promise();

  console.log(`Deleted the deny policy: ${policy.name}`);
}

deleteDenyPolicy();

Python

IAM용 클라이언트 라이브러리를 설치하고 사용하는 방법은 IAM 클라이언트 라이브러리를 참조하세요. 자세한 내용은 IAM Python API 참고 문서를 참조하세요.

IAM에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 시작하기 전에를 참조하세요.

def delete_deny_policy(project_id: str, policy_id: str) -> None:
    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    """
    Delete the policy if you no longer want to enforce the rules in a deny policy.

    project_id: ID or number of the Google Cloud project you want to use.
    policy_id: The ID of the deny policy you want to retrieve.
    """
    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    request = types.DeletePolicyRequest()
    # Construct the full path of the policy.
    # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
    request.name = f"policies/{attachment_point}/denypolicies/{policy_id}"

    # Create the DeletePolicy request.
    result = policies_client.delete_policy(request=request).result()
    print(f"Deleted the deny policy: {result.name.rsplit('/')[-1]}")

if __name__ == "__main__":
    import uuid

    # Your Google Cloud project ID.
    project_id = "your-google-cloud-project-id"
    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    delete_deny_policy(project_id, policy_id)

REST

policies.delete 메서드는 리소스에서 거부 정책을 삭제합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • ENCODED_ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 URL 인코딩 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

  • POLICY_ID: 거부 정책의 식별자입니다.
  • ETAG: (선택사항) 정책 버전에 대한 식별자입니다. 존재하는 경우 이 값이 정책의 현재 etag 값과 일치해야 합니다.

HTTP 메서드 및 URL:

DELETE https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID?etag=ETAG

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/8223fe308bf1ff01",
  "metadata": {
    "@type": "type.googleapis.com/google.iam.v2.PolicyOperationMetadata",
    "createTime": "2021-10-05T19:45:00.133311Z"
  },
  "response": {
    "@type": "type.googleapis.com/google.iam.v2.Policy",
    "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
    "kind": "DenyPolicy",
    "displayName": "My deny policy.",
    "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
    "createTime": "2022-06-28T19:06:12.455151Z",
    "updateTime": "2022-07-05T19:45:00.133311Z",
    "deleteTime": "2022-07-05T19:45:00.133311Z",
    "rules": [
      {
        "denyRule": {
          "deniedPrincipals": [
            "principal://goog/subject/lucian@example.com"
          ],
          "deniedPermissions": [
            "iam.googleapis.com/roles.create"
          ]
        }
      }
    ]
  }
}

응답은 장기 실행 작업을 식별합니다. 장기 실행 작업의 상태를 모니터링하여 완료되는 시간을 찾아낼 수 있습니다. 자세한 내용은 이 페이지에서 장기 실행 작업의 상태 확인을 참조하세요.

장기 실행 작업의 상태 확인

REST API 또는 클라이언트 라이브러리를 사용할 때 거부 정책을 변경하는 메서드는 장기 실행 작업 또는 LRO를 반환합니다. 장기 실행 작업은 요청의 상태를 추적하고 정책 변경이 완료되었는지 여부를 나타냅니다.

Go

이 페이지의 코드 샘플은 장기 실행 작업이 완료될 때까지 기다린 후 결과에 액세스하는 방법을 보여줍니다.

Java

이 페이지의 코드 샘플은 장기 실행 작업이 완료될 때까지 기다린 후 결과에 액세스하는 방법을 보여줍니다.

Node.js

이 페이지의 코드 샘플은 장기 실행 작업이 완료될 때까지 기다린 후 결과에 액세스하는 방법을 보여줍니다.

Python

이 페이지의 코드 샘플은 장기 실행 작업이 완료될 때까지 기다린 후 결과에 액세스하는 방법을 보여줍니다.

REST

policies.operations.get 메서드는 장기 실행 작업의 상태를 반환합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • ENCODED_ATTACHMENT_POINT: 거부 정책이 연결된 리소스의 URL 인코딩 식별자입니다. 이 값의 형식을 지정하는 방법은 이 페이지의 연결 지점 식별을 참조하세요.

  • OPERATION_ID: 작업의 식별자입니다. 작업 이름의 일부로 원래 요청에 대한 응답으로 이 식별자가 수신됩니다. 작업 이름의 끝에 16진수 값을 사용합니다. 예를 들면 89cb3e508bf1ff01입니다.

HTTP 메서드 및 URL:

GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/operations/OPERATION_ID

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/89cb3e508bf1ff01",
  "done": true
}

작업의 done 필드가 없으면 작업을 반복적으로 가져와서 해당 상태를 계속 모니터링합니다. 잘린 지수 백오프를 사용하여 각 요청 간에 지연을 일으킵니다. done 필드가 true로 설정되었으면 작업이 완료되었고 작업 가져오기를 중지할 수 있습니다.

다음 단계