Deny access to resources Stay organized with collections Save and categorize content based on your preferences.
This page explains how to deny principals access by preventing them from usingspecific Identity and Access Management (IAM) permissions.
In IAM, you deny access withdeny policies. Each deny policy isattached to a Google Cloud organization, folder, or project. A deny policycontainsdeny rules, which identify principals and list the permissions thatthe principals cannot use.
Deny policies are separate fromallow policies, also known asIAM policies. An allow policy provides access to resources bygranting IAM roles to principals.
You can manage deny policies with the Google Cloud console, Google Cloud CLI,or the IAMv2 REST API.
Before you begin
Enable the IAM API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.Set up authentication.
Select the tab for how you plan to use the samples on this page:
Console
When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.
gcloud
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, aCloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.
Terraform
To use the Terraform samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.
Go
To use the Go samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.
Java
To use the Java samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.
Node.js
To use the Node.js samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.
Python
To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.
REST
To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
For more information, seeAuthenticate for using REST in the Google Cloud authentication documentation.
Read theoverview of deny policies.
Required roles
To get the permissions that you need to manage deny policies, ask your administrator to grant you the following IAM roles on the organization:
- To view deny policies:Deny Reviewer (
roles/iam.denyReviewer) - To view, create, update, and delete deny policies:Deny Admin (
roles/iam.denyAdmin)
For more information about granting roles, seeManage access to projects, folders, and organizations.
These predefined roles contain the permissions required to manage deny policies. To see the exact permissions that are required, expand theRequired permissions section:
Required permissions
The following permissions are required to manage deny policies:
- To view deny policies:
iam.denypolicies.getiam.denypolicies.list
- To create, update, and delete deny policies:
iam.denypolicies.createiam.denypolicies.deleteiam.denypolicies.getiam.denypolicies.update
You might also be able to get these permissions withcustom roles or otherpredefined roles.
Identify permissions to deny
Before you create a deny policy, you must decide which permissions you want todeny, and which principals should be denied these permissions.
Only some permissions can be denied. For a list of permissions that you candeny, seePermissions supported in deny policies.
In some cases, you can also use permission groups to deny sets of permissions.For more information, seePermission groups.
You manage deny policies with thev2 REST API, which requires a special formatfor permission names. For example, the permission to create anIAM custom role is named as follows:
v1API:iam.roles.createv2API:iam.googleapis.com/roles.create
Create a deny policy
You can add deny policies to organizations, folders, and projects. Each resourcecan have up to 500 deny policies.
Deny policies contain deny rules, which specify the following:
- The permissions to deny.
- The principals that are denied those permissions.
Optional: Principals that are exempt from the denial of permissions.
For example, you can deny a permission to a group, but exempt specific userswho belong to that group.
Optional: Acondition expression that specifies whenthe principals cannot use the permissions. In deny policies, conditionexpressions can only use functions forresourcetags—other functions and operators are notsupported.
Each resource can have up to 500 deny rulesacross all of its attached deny policies.
Deny policies are inherited through theresource hierarchy. For example, if you deny a permissionat the organization level, that permission will also be denied on the foldersand projects within that organization, and on the service-specific resourceswithin each project.
Deny policies override allow policies. If a principal is granted a role thatcontains a specific permission, but a deny policy says that the principal cannotuse that permission, then the principal cannot use the permission.
Note: In general, policy changes take effect within 2 minutes. However, in some cases, itcan take 7 minutes or more for changes to propagate across the system.Console
In the Google Cloud console, go to theDeny tab on theIAM page.
Select a project, folder, or organization.
ClickCreate deny policy.
In thePolicy name section, define the policy ID by doing one of thefollowing:
- In theDisplay name field, enter a display name for the policy.Filling out this field automatically fills out theID field. If youwant to change the ID of the policy, update the text in theID field.
- In theID field, enter an ID for the policy.
In theDeny rules section, define the policy's deny rules. Each denypolicy must have at least one deny rule. To add additional deny rules, clickAdd deny rule.
For each deny rule, do the following:
- In theDenied principals field, add one or more principals that youwant to prevent from using the specified permissions. The principal canbe any of the principal types in theprincipal identifiers for denypolicies, except the principals whose IDsbegin with
deleted:. Optional: In theException principals field, add the principals thatyou want to be able to use the specified permissions, even if thoseprincipals are included inDenied principals section. For example,you can use this field to make an exception for specific users who belongto a denied group.
Note: If a principal set in the list of denied principals includesservice agents—for example, the principal set
principalSet://goog/public:all—then we recommend adding your service agents as exceptions in the deny rule. This helps ensure that your services continue to function properly. When adding service agents as exceptions, use the project, folder, or organization'sservice agent principal set.In theDenied permissions sections, add the permissions that you wantto deny. The permissions must besupported in denypolicies.
In some cases, you can also use permission groups to deny sets ofpermissions. For more information, seePermissiongroups.
Optional: Add exception permissions. Exception permissions arepermissions that you don't want this deny rule to deny, even if they'reincluded in the list of denied permissions. For example, you can use thisfield to make exceptions for specific permissions in a permission group.
To add exception permissions, clickExceptionpermissions, clickAddanother permission, and then enter the permission in thePermission1 field. Continue adding permissions until you've added all permissionsthat you want to exempt from the deny policy.
Optional: Add a denial condition to specify when the principals can't usethe permission. To add a denial condition, click
- Title: Optional. A brief summary of the purpose of the condition.
- Description: Optional. A longer description of the condition.
Condition expression: You can add a condition expression using theCondition builder orCondition editor. The condition builderprovides an interactive interface to select your desired conditiontype, operator, and other applicable details about the expression. Thecondition editor provides a text-based interface to manually enter anexpression usingCommon Expression Language (CEL) syntax.
Denial conditions must be based onresourcetags. Other functions and operators aren'tsupported.
- In theDenied principals field, add one or more principals that youwant to prevent from using the specified permissions. The principal canbe any of the principal types in theprincipal identifiers for denypolicies, except the principals whose IDsbegin with
ClickCreate.
gcloud
To create a deny policy for a resource, start by creating a JSON file thatcontains the policy. A deny policy uses the following format:
{"displayName":"POLICY_NAME","rules":[{"denyRule":DENY_RULE_1},{"denyRule":DENY_RULE_2},{"denyRule":DENY_RULE_N}]}
Provide the following values:
POLICY_NAME: The display name for the deny policy.DENY_RULE_1,DENY_RULE_2,...DENY_RULE_N: The deny rules in the policy. Each deny rule can contain these fields:deniedPermissions: A list of permissions that the specified principals cannot use. The permissions must besupported in deny policies.In some cases, you can also use permission groups to deny sets of permissions. For more information, seePermission groups.
exceptionPermissions: A list of permissions that the specified principals can use, even if those permissions are included indeniedPermissions. For example, you can use this field to make exceptions for specific permissions in a group of permissions.deniedPrincipals: A list of principals that cannot use the specified permissions. To learn how to format the principal identifiers, seePrincipal identifiers for deny policies.
Note: If a principal set in the list of denied principals includesservice agents—for example, the principal setexceptionPrincipals: Optional. A list of principals that can use the specified permissions, even if those principals are included indeniedPrincipals. For example, you can use this field to make an exception for specific users who belong to a denied group. To learn how to format the principal identifiers, seePrincipal identifiers for deny policies.principalSet://goog/public:all—then we recommend adding your service agents as exceptions in the deny rule. This helps ensure that your services continue to function properly. When adding service agents as exceptions, use the project, folder, or organization'sservice agent principal set.denialCondition: Optional. Acondition expression that specifies when the principals cannot use the permissions. Contains the following fields:expression: A condition expression that usesCommon Expression Language (CEL) syntax. The expression must use theCEL functions for evaluating resource tags. Other functions and operators are not supported.title: Optional. A brief summary of the purpose of the condition.description: Optional. A longer description of the condition.
For examples of deny rules, seeCommon use cases.
For example, the following deny policy contains one deny rule, which denies onepermission to Lucian:
{"displayName":"My deny policy.","rules":[{"denyRule":{"deniedPrincipals":["principal://goog/subject/lucian@example.com"],"deniedPermissions":["iam.googleapis.com/roles.create"]}}]}Next, run thegcloud iam policies create command:
gcloudiampoliciescreatePOLICY_ID\--attachment-point=ATTACHMENT_POINT\--kind=denypolicies\--policy-file=POLICY_FILE
Provide the following values:
POLICY_ID: The identifier for the deny policy.ATTACHMENT_POINT: An identifier for the resource thatthe deny policy is attached to. To learn how to format this value, seeAttachment point.POLICY_FILE: The filepath for the JSON file thatcontains the deny policy.
By default, if this command succeeds, it does not print any output. To print adetailed response, add the flag--format=json to the command.
For example, the following command creates a deny policy namedmy-deny-policyfor the projectmy-project, using a file namedpolicy.json:
gcloudiampoliciescreatemy-deny-policy\--attachment-point=cloudresourcemanager.googleapis.com/projects/my-project\--kind=denypolicies\--policy-file=policy.jsonTerraform
To learn how to apply or remove a Terraform configuration, seeBasic Terraform commands. For more information, see theTerraform provider reference documentation.
data"google_project""default"{}# Create a service accountresource"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 accountresource"google_iam_deny_policy""default"{provider=google-betaparent=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
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"cloud.google.com/go/iam/apiv2""cloud.google.com/go/iam/apiv2/iampb""google.golang.org/genproto/googleapis/type/expr")// createDenyPolicy creates a deny policy.funccreateDenyPolicy(wio.Writer,projectID,policyIDstring)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)iferr!=nil{returnfmt.Errorf("NewPoliciesClient: %w",err)}deferpoliciesClient.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-identifiersDeniedPrincipals:[]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-permissionsDeniedPermissions:[]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-policyDenialCondition:&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)iferr!=nil{returnfmt.Errorf("unable to create policy: %w",err)}policy,err=op.Wait(ctx)iferr!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Policy %s created\n",policy.GetName())returnnil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.iam.v2.CreatePolicyRequest;importcom.google.iam.v2.DenyRule;importcom.google.iam.v2.PoliciesClient;importcom.google.iam.v2.Policy;importcom.google.iam.v2.PolicyRule;importcom.google.longrunning.Operation;importcom.google.type.Expr;importjava.io.IOException;importjava.net.URLEncoder;importjava.nio.charset.StandardCharsets;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateDenyPolicy{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// ID or number of the Google Cloud project you want to use.StringprojectId="your-google-cloud-project-id";// Specify the id of the Deny policy you want to create.StringpolicyId="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.publicstaticvoidcreateDenyPolicy(StringprojectId,StringpolicyId)throwsIOException,ExecutionException,InterruptedException,TimeoutException{try(PoliciesClientpoliciesClient=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.StringurlEncodedResource=URLEncoder.encode("cloudresourcemanager.googleapis.com/projects/",StandardCharsets.UTF_8);StringattachmentPoint=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}"StringpolicyParent=String.format("policies/%s/denypolicies",attachmentPoint);DenyRuledenyRule=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.Policypolicy=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.CreatePolicyRequestcreatePolicyRequest=CreatePolicyRequest.newBuilder().setParent(policyParent).setPolicy(policy).setPolicyId(policyId).build();// Build the create policy request.Operationoperation=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.Policyresponse=policiesClient.getPolicy(String.format("%s/%s",policyParent,policyId));StringpolicyName=response.getName();System.out.println("Created the deny policy: "+policyName.substring(policyName.lastIndexOf("/")+1));}}}Node.js
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMNode.js API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
/** * 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;constiamClient=newPoliciesClient();// 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".constattachmentPoint=`cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;constdenyRule={// 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-identifiersdeniedPrincipals:['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-permissionsdeniedPermissions:['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-policydenialCondition:{expression:'!resource.matchTag("12345678/env", "test")',},};asyncfunctioncreateDenyPolicy(){constrequest={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]=awaitiamClient.createPolicy(request);const[policy]=awaitoperation.promise();console.log(`Created the deny policy:${policy.name}`);}createDenyPolicy();Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
defcreate_deny_policy(project_id:str,policy_id:str)->None:"""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. """fromgoogle.cloudimportiam_v2fromgoogle.cloud.iam_v2importtypespolicies_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-identifiersdeny_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-permissionsdeny_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-policydeny_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_rulepolicy=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=policyrequest.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__":importuuid# Your Google Cloud project ID.PROJECT_ID=os.getenv("GOOGLE_CLOUD_PROJECT","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
Thepolicies.createPolicy method creates a deny policy for a resource.
Before using any of the request data, make the following replacements:
ENCODED_ATTACHMENT_POINT: A URL-encoded identifier for the resource that the deny policy is attached to. To learn how to format this value, seeAttachment point.POLICY_ID: An identifier for the deny policy.POLICY_NAME: The display name for the denypolicy.DENY_RULE_1,DENY_RULE_2,...DENY_RULE_N: The deny rules in the policy. Each deny rule can contain these fields:deniedPermissions: A list of permissions that the specified principals cannot use. The permissions must besupported in deny policies.In some cases, you can also use permission groups to deny sets of permissions. For more information, seePermission groups.
exceptionPermissions: A list of permissions that the specified principals can use, even if those permissions are included indeniedPermissions. For example, you can use this field to make exceptions for specific permissions in a group of permissions.deniedPrincipals: A list of principals that cannot use the specified permissions. To learn how to format the principal identifiers, seePrincipal identifiers for deny policies.
Note: If a principal set in the list of denied principals includesservice agents—for example, the principal setexceptionPrincipals: Optional. A list of principals that can use the specified permissions, even if those principals are included indeniedPrincipals. For example, you can use this field to make an exception for specific users who belong to a denied group. To learn how to format the principal identifiers, seePrincipal identifiers for deny policies.principalSet://goog/public:all—then we recommend adding your service agents as exceptions in the deny rule. This helps ensure that your services continue to function properly. When adding service agents as exceptions, use the project, folder, or organization'sservice agent principal set.denialCondition: Optional. Acondition expression that specifies when the principals cannot use the permissions. Contains the following fields:expression: A condition expression that usesCommon Expression Language (CEL) syntax. The expression must use theCEL functions for evaluating resource tags. Other functions and operators are not supported.title: Optional. A brief summary of the purpose of the condition.description: Optional. A longer description of the condition.
For examples of deny rules, seeCommon use cases.
HTTP method and URL:
POST https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies?policyId=POLICY_ID
Request JSON body:
{ "displayName": "POLICY_NAME", "rules": [ { "denyRule":DENY_RULE_1 }, { "denyRule":DENY_RULE_2 }, { "denyRule":DENY_RULE_N } ]}To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies?policyId=POLICY_ID"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies?policyId=POLICY_ID" | Select-Object -Expand Content
APIs Explorer (browser)
Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.
You should receive a JSON response similar to the following:
{ "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" ] } } ] }}The response identifies a long-running operation. You can monitor the status of the long-running operation to find out when it's complete. For details, seeCheck the status of a long-running operation on this page.
List deny policies
A resource can have multiple deny policies. You can list all of the denypolicies that are attached to a resource, and thenview each denypolicy to see the deny rules in each policy.
Console
In the Google Cloud console, go to theDeny tab on theIAM page.
Select a project, folder, or organization.
The Google Cloud console lists all deny policies that apply to thatproject, folder, or organization. This includes deny policies that have beeninherited from other resources. For more information about deny policyinheritance, seeDeny policy inheritance.
gcloud
To list the deny policies for a resource, run thegcloud iam policies list command:
gcloudiampolicieslist\--attachment-point=ATTACHMENT_POINT\--kind=denypolicies\--format=json
Provide the following value:
ATTACHMENT_POINT: An identifier for the resource thatthe deny policy is attached to. To learn how to format this value, seeAttachment point.
For example, the following command lists deny policies attached to anorganization whose numeric ID is123456789012:
gcloudiampolicieslist\--attachment-point=cloudresourcemanager.googleapis.com/organizations/123456789012\--kind=denypolicies\--format=jsonGo
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"cloud.google.com/go/iam/apiv2""cloud.google.com/go/iam/apiv2/iampb""google.golang.org/api/iterator")// listDenyPolicies lists all the deny policies that are attached to a resource.// A resource can have up to 5 deny policies.funclistDenyPolicies(wio.Writer,projectIDstring)error{// projectID := "your_project_id"ctx:=context.Background()policiesClient,err:=iam.NewPoliciesClient(ctx)iferr!=nil{returnfmt.Errorf("NewPoliciesClient: %w",err)}deferpoliciesClient.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()iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Fprintf(w,"- %s\n",policy.GetName())}returnnil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.iam.v2.PoliciesClient;importcom.google.iam.v2.Policy;importjava.io.IOException;importjava.net.URLEncoder;importjava.nio.charset.StandardCharsets;publicclassListDenyPolicies{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace these variables before running the sample.// ID or number of the Google Cloud project you want to use.StringprojectId="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.publicstaticvoidlistDenyPolicies(StringprojectId)throwsIOException{// Initialize the Policies client.try(PoliciesClientpoliciesClient=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.StringurlEncodedResource=URLEncoder.encode("cloudresourcemanager.googleapis.com/projects/",StandardCharsets.UTF_8);StringattachmentPoint=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"StringpolicyParent=String.format("policies/%s/denypolicies",attachmentPoint);// Create a list request and iterate over the returned policies.for(Policypolicy:policiesClient.listPolicies(policyParent).iterateAll()){System.out.println(policy.getName());}System.out.println("Listed all deny policies");}}}Node.js
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMNode.js API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
/** * TODO(developer): Uncomment and replace these variables before running the sample. */// const projectId = 'YOUR_PROJECT_ID';const{PoliciesClient}=require('@google-cloud/iam').v2;constiamClient=newPoliciesClient();// 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".constattachmentPoint=`cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;asyncfunctionlistDenyPolicies(){constrequest={parent:`policies/${attachmentPoint}/denypolicies`,};constpolicies=awaitiamClient.listPoliciesAsync(request);forawait(constpolicyofpolicies){console.log(`-${policy.name}`);}}listDenyPolicies();Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
deflist_deny_policy(project_id:str)->None:"""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. """fromgoogle.cloudimportiam_v2fromgoogle.cloud.iam_v2importtypespolicies_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)forpolicyinpolicies:print(policy.name)print("Listed all deny policies")if__name__=="__main__":# Your Google Cloud project ID.PROJECT_ID=os.getenv("GOOGLE_CLOUD_PROJECT","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
Thepolicies.listPolicies method lists the deny policies for a resource.
Before using any of the request data, make the following replacements:
ENCODED_ATTACHMENT_POINT: A URL-encoded identifier for the resource that the deny policy is attached to. To learn how to format this value, seeAttachment point.
HTTP method and URL:
GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies
To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.Execute the following command:
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.Execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies" | Select-Object -Expand Content
APIs Explorer (browser)
Open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Complete any required fields and clickExecute.
You should receive a JSON response similar to the following:
{ "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" } ]}View a deny policy
You can view a deny policy to see the deny rules that it contains, including thepermissions that are denied and the principals who cannot use those permissions.
Console
In the Google Cloud console, go to theDeny tab on theIAM page.
Select a project, folder, or organization.
In thePolicy ID column, click the ID of the policy that you want toview.
The Google Cloud console shows the details of the deny policy, includingthe policy ID, when the policy was created, and the deny rules in the denypolicy.
gcloud
To get the deny policy for a resource, run thegcloud iam policies get command:
gcloudiampoliciesgetPOLICY_ID\--attachment-point=ATTACHMENT_POINT\--kind=denypolicies\--format=json
Provide the following values:
POLICY_ID: The identifier for the deny policy.ATTACHMENT_POINT: An identifier for the resource thatthe deny policy is attached to. To learn how to format this value, seeAttachment point.
For example, the following command gets the deny policy namedmy-deny-policyfor the projectmy-project and saves it in a file namedpolicy.json:
gcloudiampoliciesgetmy-deny-policy\--attachment-point=cloudresourcemanager.googleapis.com/projects/my-project\--kind=denypolicies\--format=json\ >./policy.jsonGo
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"cloud.google.com/go/iam/apiv2""cloud.google.com/go/iam/apiv2/iampb")// getDenyPolicy retrieves the deny policy given the project ID and policy ID.funcgetDenyPolicy(wio.Writer,projectID,policyIDstring)error{// projectID := "your_project_id"// policyID := "your_policy_id"ctx:=context.Background()policiesClient,err:=iam.NewPoliciesClient(ctx)iferr!=nil{returnfmt.Errorf("NewPoliciesClient: %w",err)}deferpoliciesClient.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)iferr!=nil{returnfmt.Errorf("unable to get policy: %w",err)}fmt.Fprintf(w,"Policy %s retrieved\n",policy.GetName())returnnil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.iam.v2.GetPolicyRequest;importcom.google.iam.v2.PoliciesClient;importcom.google.iam.v2.Policy;importjava.io.IOException;importjava.net.URLEncoder;importjava.nio.charset.StandardCharsets;publicclassGetDenyPolicy{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace these variables before running the sample.// ID or number of the Google Cloud project you want to use.StringprojectId="your-google-cloud-project-id";// Specify the ID of the deny policy you want to retrieve.StringpolicyId="deny-policy-id";getDenyPolicy(projectId,policyId);}// Retrieve the deny policy given the project ID and policy ID.publicstaticvoidgetDenyPolicy(StringprojectId,StringpolicyId)throwsIOException{// Create the IAM Policies client.try(PoliciesClientpoliciesClient=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.StringurlEncodedResource=URLEncoder.encode("cloudresourcemanager.googleapis.com/projects/",StandardCharsets.UTF_8);StringattachmentPoint=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}"StringpolicyParent=String.format("policies/%s/denypolicies/%s",attachmentPoint,policyId);// Specify the policyParent and execute the GetPolicy request.GetPolicyRequestgetPolicyRequest=GetPolicyRequest.newBuilder().setName(policyParent).build();Policypolicy=policiesClient.getPolicy(getPolicyRequest);System.out.printf("Retrieved the deny policy: %s : %s%n",policyId,policy);}}}Node.js
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMNode.js API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
/** * 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;constiamClient=newPoliciesClient();// 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".constattachmentPoint=`cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;asyncfunctiongetDenyPolicy(){constrequest={name:`policies/${attachmentPoint}/denypolicies/${policyId}`,};const[policy]=awaitiamClient.getPolicy(request);console.log(`Retrieved the deny policy:${policy.name}`);}getDenyPolicy();Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
fromgoogle.cloudimportiam_v2fromgoogle.cloud.iam_v2importPolicy,typesdefget_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}")returnpolicyif__name__=="__main__":# Your Google Cloud project ID.PROJECT_ID=os.getenv("GOOGLE_CLOUD_PROJECT","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
Thepolicies.get method gets a deny policy for a resource.
Before using any of the request data, make the following replacements:
ENCODED_ATTACHMENT_POINT: A URL-encoded identifier for the resource that the deny policy is attached to. To learn how to format this value, seeAttachment point.POLICY_ID: An identifier for the deny policy.
HTTP method and URL:
GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID
To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.Execute the following command:
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.Execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID" | Select-Object -Expand Content
APIs Explorer (browser)
Open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Complete any required fields and clickExecute.
You should receive a JSON response similar to the following:
{ "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" ] } } ]}Update a deny policy
After you create a deny policy, you can update the deny rules that it contains,as well as its display name.
You can update a deny policy using the Google Cloud console, or usingone of the following programmatic methods:
- The gcloud CLI
- The REST API
- The IAM client libraries
Update a deny policy using the Google Cloud console
In the Google Cloud console, go to theDeny tab on theIAM page.
Select a project, folder, or organization.
In thePolicy ID column, click the ID of the policy that you want toedit.
ClickEdit.
Update the deny policy:
- To change the policy display name, edit theDisplay name field.
- To edit an existing deny rule, click the deny rule, and then modify therule's principals, exception principals, denied permissions, exceptionpermissions, or denial condition.
- To remove a deny rule, find the deny rule that you want to delete, andthen clickDelete in thatrow.
- To add a deny rule, clickAdd deny rule, and then create a deny rulelike you do when youcreate a deny policy.
When you're done updating the deny policy, clickSave.
Update a deny policy programmatically
To update a deny policy using the gcloud CLI, the REST API, or theIAM client libraries, use theread-modify-write pattern:
- Read the current version of the policy.
- Modify the information in the policy as needed.
- Write the updated policy.
Read the deny policy
gcloud
To get the deny policy for a resource, run thegcloud iam policies get command:
gcloudiampoliciesgetPOLICY_ID\--attachment-point=ATTACHMENT_POINT\--kind=denypolicies\--format=json
Provide the following values:
POLICY_ID: The identifier for the deny policy.ATTACHMENT_POINT: An identifier for the resource thatthe deny policy is attached to. To learn how to format this value, seeAttachment point.
For example, the following command gets the deny policy namedmy-deny-policyfor the projectmy-project and saves it in a file namedpolicy.json:
gcloudiampoliciesgetmy-deny-policy\--attachment-point=cloudresourcemanager.googleapis.com/projects/my-project\--kind=denypolicies\--format=json\ >./policy.jsonGo
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"cloud.google.com/go/iam/apiv2""cloud.google.com/go/iam/apiv2/iampb")// getDenyPolicy retrieves the deny policy given the project ID and policy ID.funcgetDenyPolicy(wio.Writer,projectID,policyIDstring)error{// projectID := "your_project_id"// policyID := "your_policy_id"ctx:=context.Background()policiesClient,err:=iam.NewPoliciesClient(ctx)iferr!=nil{returnfmt.Errorf("NewPoliciesClient: %w",err)}deferpoliciesClient.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)iferr!=nil{returnfmt.Errorf("unable to get policy: %w",err)}fmt.Fprintf(w,"Policy %s retrieved\n",policy.GetName())returnnil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.iam.v2.GetPolicyRequest;importcom.google.iam.v2.PoliciesClient;importcom.google.iam.v2.Policy;importjava.io.IOException;importjava.net.URLEncoder;importjava.nio.charset.StandardCharsets;publicclassGetDenyPolicy{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace these variables before running the sample.// ID or number of the Google Cloud project you want to use.StringprojectId="your-google-cloud-project-id";// Specify the ID of the deny policy you want to retrieve.StringpolicyId="deny-policy-id";getDenyPolicy(projectId,policyId);}// Retrieve the deny policy given the project ID and policy ID.publicstaticvoidgetDenyPolicy(StringprojectId,StringpolicyId)throwsIOException{// Create the IAM Policies client.try(PoliciesClientpoliciesClient=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.StringurlEncodedResource=URLEncoder.encode("cloudresourcemanager.googleapis.com/projects/",StandardCharsets.UTF_8);StringattachmentPoint=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}"StringpolicyParent=String.format("policies/%s/denypolicies/%s",attachmentPoint,policyId);// Specify the policyParent and execute the GetPolicy request.GetPolicyRequestgetPolicyRequest=GetPolicyRequest.newBuilder().setName(policyParent).build();Policypolicy=policiesClient.getPolicy(getPolicyRequest);System.out.printf("Retrieved the deny policy: %s : %s%n",policyId,policy);}}}Node.js
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMNode.js API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
/** * 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;constiamClient=newPoliciesClient();// 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".constattachmentPoint=`cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;asyncfunctiongetDenyPolicy(){constrequest={name:`policies/${attachmentPoint}/denypolicies/${policyId}`,};const[policy]=awaitiamClient.getPolicy(request);console.log(`Retrieved the deny policy:${policy.name}`);}getDenyPolicy();Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
fromgoogle.cloudimportiam_v2fromgoogle.cloud.iam_v2importPolicy,typesdefget_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}")returnpolicyif__name__=="__main__":# Your Google Cloud project ID.PROJECT_ID=os.getenv("GOOGLE_CLOUD_PROJECT","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
Thepolicies.get method gets a deny policy for a resource.
Before using any of the request data, make the following replacements:
ENCODED_ATTACHMENT_POINT: A URL-encoded identifier for the resource that the deny policy is attached to. To learn how to format this value, seeAttachment point.POLICY_ID: An identifier for the deny policy.
HTTP method and URL:
GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID
To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.Execute the following command:
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.Execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID" | Select-Object -Expand Content
APIs Explorer (browser)
Open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Complete any required fields and clickExecute.
You should receive a JSON response similar to the following:
{ "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" ] } } ]}Modify the deny policy
To modify the deny policy, you make changes to the copy of the policy that youpreviously read from IAM. You can update the display name, or youcan add, change, or remove deny rules. The changes don't take effect until youwrite the updated policy.
Note: In general, policy changes take effect within 2 minutes. However, in some cases, itcan take 7 minutes or more for changes to propagate across the system.For example, you could add a permission to an existing deny rule:
{"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"]}}]}
Write the updated deny policy
After youmodify the deny policy locally, you must writethe updated deny policy to IAM.
Each deny policy contains anetag field that identifies the policy version.Theetag changes each time you update the policy. When you write the updatedpolicy, theetag in your request must match the currentetag stored inIAM; if the values do not match, the request fails. This featurehelps prevent concurrent changes from overwriting each other.
gcloud
To update the deny policy for a resource, run thegcloud iam policies update command:
gcloudiampoliciesupdatePOLICY_ID\--attachment-point=ATTACHMENT_POINT\--kind=denypolicies\--policy-file=POLICY_FILE
Provide the following values:
POLICY_ID: The identifier for the deny policy.ATTACHMENT_POINT: An identifier for the resource thatthe deny policy is attached to. To learn how to format this value, seeAttachment point.POLICY_FILE: The filepath for the JSON file thatcontains the deny policy.
By default, if this command succeeds, it does not print any output. To print adetailed response, add the flag--format=json to the command.
For example, the following command updates a deny policy namedmy-deny-policyfor the projectmy-project, using a file namedpolicy.json:
gcloudiampoliciesupdatemy-deny-policy\--attachment-point=cloudresourcemanager.googleapis.com/projects/my-project\--kind=denypolicies\--policy-file=policy.jsonGo
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"cloud.google.com/go/iam/apiv2""cloud.google.com/go/iam/apiv2/iampb""google.golang.org/genproto/googleapis/type/expr")// updateDenyPolicy updates the deny rules and/ or its display name after policy creation.funcupdateDenyPolicy(wio.Writer,projectID,policyID,etagstring)error{// projectID := "your_project_id"// policyID := "your_policy_id"// etag := "your_etag"ctx:=context.Background()policiesClient,err:=iam.NewPoliciesClient(ctx)iferr!=nil{returnfmt.Errorf("NewPoliciesClient: %w",err)}deferpoliciesClient.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-identifiersDeniedPrincipals:[]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-permissionsDeniedPermissions:[]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-policyDenialCondition:&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)iferr!=nil{returnfmt.Errorf("unable to update policy: %w",err)}policy,err=op.Wait(ctx)iferr!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Policy %s updated\n",policy.GetName())returnnil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.iam.v2.DenyRule;importcom.google.iam.v2.PoliciesClient;importcom.google.iam.v2.Policy;importcom.google.iam.v2.PolicyRule;importcom.google.iam.v2.UpdatePolicyRequest;importcom.google.longrunning.Operation;importcom.google.type.Expr;importjava.io.IOException;importjava.net.URLEncoder;importjava.nio.charset.StandardCharsets;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassUpdateDenyPolicy{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// ID or number of the Google Cloud project you want to use.StringprojectId="your-google-cloud-project-id";// Specify the ID of the Deny policy you want to retrieve.StringpolicyId="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.Stringetag="policy_etag";updateDenyPolicy(projectId,policyId,etag);}// Update the deny rules and/ or its display name after policy creation.publicstaticvoidupdateDenyPolicy(StringprojectId,StringpolicyId,Stringetag)throwsIOException,ExecutionException,InterruptedException,TimeoutException{try(PoliciesClientpoliciesClient=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.StringurlEncodedResource=URLEncoder.encode("cloudresourcemanager.googleapis.com/projects/",StandardCharsets.UTF_8);StringattachmentPoint=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}"StringpolicyParent=String.format("policies/%s/denypolicies/%s",attachmentPoint,policyId);DenyRuledenyRule=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.Policypolicy=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.UpdatePolicyRequestupdatePolicyRequest=UpdatePolicyRequest.newBuilder().setPolicy(policy).build();// Wait for the operation to complete.Operationoperation=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
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMNode.js API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
/** * 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;constiamClient=newPoliciesClient();// 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".constattachmentPoint=`cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;constdenyRule={// 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-identifiersdeniedPrincipals:['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-permissionsdeniedPermissions:['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-policydenialCondition:{expression:'!resource.matchTag("12345678/env", "prod")',},};asyncfunctionupdateDenyPolicy(){constrequest={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]=awaitiamClient.updatePolicy(request);const[policy]=awaitoperation.promise();console.log(`Updated the deny policy:${policy.name}`);}updateDenyPolicy();Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
defupdate_deny_policy(project_id:str,policy_id:str,etag:str)->None:"""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. """fromgoogle.cloudimportiam_v2fromgoogle.cloud.iam_v2importtypespolicies_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-identifiersdeny_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-permissionsdeny_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-policydeny_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=etagpolicy.rules=[policy_rule]# Create the update policy request.request=types.UpdatePolicyRequest()request.policy=policyresult=policies_client.update_policy(request=request).result()print(f"Updated the deny policy:{result.name.rsplit('/')[-1]}")if__name__=="__main__":# Your Google Cloud project ID.PROJECT_ID=os.getenv("GOOGLE_CLOUD_PROJECT","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
Thepolicies.update method updates a deny policy.
Before using any of the request data, make the following replacements:
ENCODED_ATTACHMENT_POINT: A URL-encoded identifier for the resource that the deny policy is attached to. To learn how to format this value, seeAttachment point.POLICY_ID: An identifier for the deny policy.POLICY: The updated deny policy.For example, to add a permission to the policy shown in the previous step, replace
POLICYwith the following:{"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 method and URL:
PUT https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID
Request JSON body:
POLICY
To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
curl -X PUT \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method PUT `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID" | Select-Object -Expand Content
APIs Explorer (browser)
Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.
You should receive a JSON response similar to the following:
{ "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" ] } } ] }}The response identifies a long-running operation. You can monitor the status of the long-running operation to find out when it's complete. For details, seeCheck the status of a long-running operation on this page.
Delete a deny policy
If you no longer want to enforce the rules in a deny policy, you can delete thedeny policy.
Caution: Deleting a deny policy is permanent. You cannot undelete deny policies.Optionally, you can specify theetag for the policy version that you aredeleting. If you specify theetag, it must match the currentetag stored byIAM; if the values do not match, the request fails. You can usethis feature to ensure that you are deleting the intended policy, rather than anupdated version of that policy.
If you omit theetag from the request, IAM deletes the policyunconditionally.
Console
In the Google Cloud console, go to theDeny tab on theIAM page.
Select a project, folder, or organization.
In thePolicy ID column, click the ID of the policy that you want todelete.
ClickDelete. In theconfirmation dialog, clickConfirm.
gcloud
To delete a deny policy from a resource, run thegcloud iam policies delete command:
gcloudiampoliciesdeletePOLICY_ID\--attachment-point=ATTACHMENT_POINT\--kind=denypolicies
Provide the following values:
POLICY_ID: The identifier for the deny policy.ATTACHMENT_POINT: An identifier for the resource thatthe deny policy is attached to. To learn how to format this value, seeAttachment point.
Optionally, you can add the flag--etag=ETAG. ReplaceETAG with the currentetag value for the deny policy.
By default, if this command succeeds, it does not print any output. To print adetailed response, add the flag--format=json to the command.
For example, the following command deletes a deny policy namedmy-deny-policyfrom the projectmy-project:
gcloudiampoliciesdeletemy-deny-policy\--attachment-point=cloudresourcemanager.googleapis.com/projects/my-project\--kind=denypoliciesGo
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMGo API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
import("context""fmt""io"iam"cloud.google.com/go/iam/apiv2""cloud.google.com/go/iam/apiv2/iampb")// deleteDenyPolicy deletes the policy if you no longer want to enforce the rules in a deny policy.funcdeleteDenyPolicy(wio.Writer,projectID,policyIDstring)error{// projectID := "your_project_id"// policyID := "your_policy_id"ctx:=context.Background()policiesClient,err:=iam.NewPoliciesClient(ctx)iferr!=nil{returnfmt.Errorf("NewPoliciesClient: %w",err)}deferpoliciesClient.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)iferr!=nil{returnfmt.Errorf("unable to delete policy: %w",err)}policy,err:=op.Wait(ctx)iferr!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Policy %s deleted\n",policy.GetName())returnnil}Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
importcom.google.iam.v2.DeletePolicyRequest;importcom.google.iam.v2.PoliciesClient;importcom.google.longrunning.Operation;importjava.io.IOException;importjava.net.URLEncoder;importjava.nio.charset.StandardCharsets;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassDeleteDenyPolicy{publicstaticvoidmain(String[]args)throwsIOException,InterruptedException,ExecutionException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// ID or number of the Google Cloud project you want to use.StringprojectId="your-google-cloud-project-id";// Specify the ID of the deny policy you want to retrieve.StringpolicyId="deny-policy-id";deleteDenyPolicy(projectId,policyId);}// Delete the policy if you no longer want to enforce the rules in a deny policy.publicstaticvoiddeleteDenyPolicy(StringprojectId,StringpolicyId)throwsIOException,InterruptedException,ExecutionException,TimeoutException{try(PoliciesClientpoliciesClient=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.StringurlEncodedResource=URLEncoder.encode("cloudresourcemanager.googleapis.com/projects/",StandardCharsets.UTF_8);StringattachmentPoint=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}"StringpolicyParent=String.format("policies/%s/denypolicies/%s",attachmentPoint,policyId);// Create the DeletePolicy request.DeletePolicyRequestdeletePolicyRequest=DeletePolicyRequest.newBuilder().setName(policyParent).build();// Delete the policy and wait for the operation to complete.Operationoperation=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
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMNode.js API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
/** * 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;constiamClient=newPoliciesClient();// 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".constattachmentPoint=`cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;asyncfunctiondeleteDenyPolicy(){constrequest={name:`policies/${attachmentPoint}/denypolicies/${policyId}`,};const[operation]=awaitiamClient.deletePolicy(request);const[policy]=awaitoperation.promise();console.log(`Deleted the deny policy:${policy.name}`);}deleteDenyPolicy();Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
defdelete_deny_policy(project_id:str,policy_id:str)->None:"""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. """fromgoogle.cloudimportiam_v2fromgoogle.cloud.iam_v2importtypespolicies_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__":importuuid# Your Google Cloud project ID.PROJECT_ID=os.getenv("GOOGLE_CLOUD_PROJECT","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
Thepolicies.delete method deletes a deny policy from a resource.
Before using any of the request data, make the following replacements:
ENCODED_ATTACHMENT_POINT: A URL-encoded identifier for the resource that the deny policy is attached to. To learn how to format this value, seeAttachment point.POLICY_ID: An identifier for the deny policy.ETAG: Optional. An identifier for the version of the policy. If present, this value must match the currentetagvalue for the policy.
HTTP method and URL:
DELETE https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID?etag=ETAG
To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.Execute the following command:
curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID?etag=ETAG"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.Execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID?etag=ETAG" | Select-Object -Expand Content
APIs Explorer (browser)
Open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Complete any required fields and clickExecute.
You should receive a JSON response similar to the following:
{ "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" ] } } ] }}The response identifies a long-running operation. You can monitor the status of the long-running operation to find out when it's complete. For details, seeCheck the status of a long-running operation on this page.
Check the status of a long-running operation
When you use the REST API or the client libraries, any method that changes adeny policy returns a long-running operation, or LRO. The long-running operationtracks the status of the request and indicates whether the change to the policyis complete.
Note: If you use the gcloud CLI, you can see the long-runningoperation by running a command with the--format=json flag. However, you mustuse the REST API or the client libraries to get the operation's status.Go
The code samples on this page show how to wait for a long-running operation tofinish, and then access its result.
Java
The code samples on this page show how to wait for a long-running operation tofinish, and then access its result.
Node.js
The code samples on this page show how to wait for a long-running operation tofinish, and then access its result.
Python
The code samples on this page show how to wait for a long-running operation tofinish, and then access its result.
REST
Thepolicies.operations.get method returns the status of a long-running operation.
Before using any of the request data, make the following replacements:
ENCODED_ATTACHMENT_POINT: A URL-encoded identifier for the resource that the deny policy is attached to. To learn how to format this value, seeAttachment point.OPERATION_ID: The identifier for the operation. You receive this identifier in the response to your original request, as part of the operation name. Use the hexadecimal value at the end of the operation name. For example,89cb3e508bf1ff01.
HTTP method and URL:
GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/operations/OPERATION_ID
To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.Execute the following command:
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/operations/OPERATION_ID"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.Execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/operations/OPERATION_ID" | Select-Object -Expand Content
APIs Explorer (browser)
Open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Complete any required fields and clickExecute.
You should receive a JSON response similar to the following:
{ "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/89cb3e508bf1ff01", "done": true}If the operation'sdone field is not present, continue to monitor its statusby getting the operation repeatedly. Usetruncated exponential backoff to introduce a delay betweeneach request. When thedone field is set totrue, the operation is complete,and you can stop getting the operation.
What's next
- Identify thepermissions that are supported in deny policies.
- Get the format ofprincipal identifiers in deny policies.
- Find out how totroubleshoot access issues with deny policies.
- Learn more aboutdenying access to principals.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.