Manage access to projects, folders, and organizations

This page describes how to grant, change, and revoke access to projects,folders, and organizations. When you grant access to projects, folders, andorganizations, you also grant access to the resources inside them.

To learn how to manage access to other resources, see the following guides:

Note: Granting access to projects, folders, and organizations is considered a sensitive action; in some cases, you might need to reauthenticate before you can initiate the action. For more information, seeSensitive actions.

In Identity and Access Management (IAM), access is granted throughallow policies, alsoknown as IAM policies. An allow policy is attached to aGoogle Cloud resource. Each allow policy contains a collection ofrolebindings that associate one or more principals, such as users or serviceaccounts, with an IAM role. These role bindings grant thespecified roles to the principals, both on the resource that the allow policy isattached to and on all of that resource'sdescendants. Formore information about allow policies, seeUnderstanding allow policies.

Note: If you're getting started with Google Cloud, you can grant theappropriate IAM roles to your organization administrator groupsas part of theGoogle Cloud setup process.

You can manage access to projects, folders, and organizations with theGoogle Cloud console, the Google Cloud CLI, the REST API, or theResource Managerclient libraries.

Note: You can also use deny policies to prevent principals from using specific IAM permissions. For more information, seeDeny policies.

Before you begin

  • Enable the Resource Manager API.

    Enable the API

  • 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.

      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.

    C#

    To use the .NET 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.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. Toinitialize the gcloud CLI, run the following command:

      gcloudinit
    4. 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.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. Toinitialize the gcloud CLI, run the following command:

      gcloudinit
    4. 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.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. Toinitialize the gcloud CLI, run the following command:

      gcloudinit
    4. 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.

      Afterinstalling the Google Cloud CLI,initialize it by running the following command:

      gcloudinit

      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.

Required IAM roles

When you create a project, folder, or organization, you are automaticallygranted a role that lets you manage access for that resource. For moreinformation, seeDefault policies.

If you didn't create your project, folder, or organization, ensure that you havethe roles that you need to manage access to that resource.

To get the permissions that you need to manage access to a project, folder, or organization, ask your administrator to grant you the following IAM roles on the resource that you want to manage access for (project,folder, or organization):

  • To manage access to a project:Project IAM Admin (roles/resourcemanager.projectIamAdmin)
  • To manage access to a folder:Folder Admin (roles/resourcemanager.folderAdmin)
  • To manage access to projects, folders, and organizations:Organization Admin (roles/resourcemanager.organizationAdmin)
  • To manage access to almost all Google Cloud resources:Security Admin (roles/iam.securityAdmin)

These predefined roles contain the permissions required to manage access to a project, folder, or organization. To see the exact permissions that are required, expand theRequired permissions section:

Required permissions

The following permissions are required to manage access to a project, folder, or organization:

  • To manage access to projects:
    • resourcemanager.projects.getIamPolicy
    • resourcemanager.projects.setIamPolicy
  • To manage access to folders:
    • resourcemanager.folders.getIamPolicy
    • resourcemanager.folders.setIamPolicy
  • To manage access to organizations:
    • resourcemanager.organizations.getIamPolicy
    • resourcemanager.organizations.setIamPolicy

You might also be able to get these permissions withcustomroles or otherpredefined roles.

View current access

You can view who has access to your project, folder, or organization usingthe Google Cloud console, the gcloud CLI, the REST API, or theResource Manager client libraries.

Console

Note: The Google Cloud console shows access in a list form, rather thandirectly showing the resource's allow policy.
  1. In the Google Cloud console, go to theIAM page.

    Go to IAM

  2. Select a project, folder, or organization.

    The Google Cloud console lists all the principals who have been grantedroles on your project, folder, or organization. This list includesprincipals who have inherited roles on the resource from parent resources.For more information about policy inheritance, seePolicy inheritance andthe resource hierarchy.

  3. Optional: To view role grants forservice agents, selecttheInclude Google-provided role grants checkbox.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    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.

  2. To see who has access to your project, folder, or organization, get the allow policy for the resource. To learn how to interpret allow policies, seeUnderstanding allow policies.

    Note: A resource's allow policy does not show any roles gained throughpolicy inheritance. To view inherited roles, use the Google Cloud console, or follow the instructions onViewing effective IAM policies.

    To get the allow policy for the resource, run theget-iam-policy command for the resource:

    gcloudRESOURCE_TYPEget-iam-policyRESOURCE_ID--format=FORMAT >PATH

    Provide the following values:

    • RESOURCE_TYPE: The type of the resource that you want to view access to. Use one of these values:projects,resource-manager folders, ororganizations.

    • RESOURCE_ID: Your Google Cloud project, folder, or organization ID. Project IDs are alphanumeric, likemy-project. Folder and organization IDs are numeric, like123456789012.

    • FORMAT: The desired format for the policy. Usejson oryaml.

    • PATH: The path to a new output file for the policy.

    For example, the following command gets the policy for the projectmy-project and saves it to your home directory in JSON format:

    gcloudprojectsget-iam-policymy-project--format=json >~/policy.json

C#

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

To see who has access to your project, folder, or organization, get the allow policy for the resource. To learn how to interpret allow policies, seeUnderstanding allow policies.

The following example shows how to get the allow policy for a project. To learn how to get the allow policy for a folder or organization, review theResource Manager client library documentation for your programming language.

usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.CloudResourceManager.v1;usingGoogle.Apis.CloudResourceManager.v1.Data;publicpartialclassAccessManager{publicstaticPolicyGetPolicy(stringprojectId){varcredential=GoogleCredential.GetApplicationDefault().CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);varservice=newCloudResourceManagerService(newCloudResourceManagerService.Initializer{HttpClientInitializer=credential});varpolicy=service.Projects.GetIamPolicy(newGetIamPolicyRequest(),projectId).Execute();returnpolicy;}}

Java

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

To see who has access to your project, folder, or organization, get the allow policy for the resource. To learn how to interpret allow policies, seeUnderstanding allow policies.

The following example shows how to get the allow policy for a project. To learn how to get the allow policy for a folder or organization, review theResource Manager client library documentation for your programming language.

importcom.google.cloud.resourcemanager.v3.ProjectsClient;importcom.google.iam.admin.v1.ProjectName;importcom.google.iam.v1.GetIamPolicyRequest;importcom.google.iam.v1.Policy;importjava.io.IOException;publicclassGetProjectPolicy{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variables before running the sample.// TODO: Replace with your project ID.StringprojectId="your-project-id";getProjectPolicy(projectId);}// Gets a project's policy.publicstaticPolicygetProjectPolicy(StringprojectId)throwsIOException{// Initialize client that will be used to send requests.// This client only needs to be created once, and can be reused for multiple requests.try(ProjectsClientprojectsClient=ProjectsClient.create()){GetIamPolicyRequestrequest=GetIamPolicyRequest.newBuilder().setResource(ProjectName.of(projectId).toString()).build();returnprojectsClient.getIamPolicy(request);}}}

Python

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

To see who has access to your project, folder, or organization, get the allow policy for the resource. To learn how to interpret allow policies, seeUnderstanding allow policies.

The following example shows how to get the allow policy for a project. To learn how to get the allow policy for a folder or organization, review theResource Manager client library documentation for your programming language.

fromgoogle.cloudimportresourcemanager_v3fromgoogle.iam.v1importiam_policy_pb2,policy_pb2defget_project_policy(project_id:str)->policy_pb2.Policy:"""Get policy for project.    project_id: ID or number of the Google Cloud project you want to use.    """client=resourcemanager_v3.ProjectsClient()request=iam_policy_pb2.GetIamPolicyRequest()request.resource=f"projects/{project_id}"policy=client.get_iam_policy(request)print(f"Policy retrieved:{policy}")returnpolicy

REST

To see who has access to your project, folder, or organization, get the allowpolicy for the resource. To learn how to interpret allow policies, seeUnderstanding allow policies.

Note: A resource's allow policy does not show any roles gained throughpolicy inheritance. To view inherited roles, use the Google Cloud console, or follow the instructions onViewing effective IAM policies.

The Resource Manager API'sgetIamPolicy method gets a project's, folder's, or organization's allow policy.

Before using any of the request data, make the following replacements:

  • API_VERSION: The API version to use. Forprojects and organizations, usev1. For folders, usev2.
  • RESOURCE_TYPE: The resource type whosepolicy you want to manage. Use the valueprojects,folders, ororganizations.
  • RESOURCE_ID: Your Google Cloudproject, organization, or folder ID. Project IDs are alphanumeric strings, likemy-project. Folder and organization IDs are numeric, like123456789012.
  • POLICY_VERSION: The policy version to bereturned. Requests should specify the most recent policy version, which is policy version3. SeeSpecifyinga policy version when getting a policy for details.

HTTP method and URL:

POST https://cloudresourcemanager.googleapis.com/API_VERSION/RESOURCE_TYPE/RESOURCE_ID:getIamPolicy

Request JSON body:

{  "options": {    "requestedPolicyVersion":POLICY_VERSION  }}

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://cloudresourcemanager.googleapis.com/API_VERSION/RESOURCE_TYPE/RESOURCE_ID:getIamPolicy"

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://cloudresourcemanager.googleapis.com/API_VERSION/RESOURCE_TYPE/RESOURCE_ID:getIamPolicy" | 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.

The response contains the resource's allow policy. For example:

{  "version": 1,  "etag": "BwWKmjvelug=",  "bindings": [    {      "role": "roles/owner",      "members": [        "user:my-user@example.com"      ]    }  ]}

Grant or revoke a single IAM role

You can use the Google Cloud console and the gcloud CLI to quicklygrant or revoke a single role for a single principal, without editing theresource's allow policy directly.Common types of principals include GoogleAccounts, service accounts, Google groups, and domains.For a list of allprincipal types, seePrincipal types.

Note: If theiam.allowedPolicyMemberDomains organization policy constraint is enforced in your organization, then you might not be able to grant roles to newly created groups. If you get afailedPrecondition error when trying to grant a role to a newly created group, wait 24 hours, and then try granting the role again.

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.

If you need help identifying the most appropriate predefined role, seeFind the right predefined roles.

Grant a single IAM role

To grant a single role to a principal, do the following:

Console

  1. In the Google Cloud console, go to theIAM page.

    Go to IAM

  2. Select a project, folder, or organization.

  3. Select a principal to grant a role to:

  4. Select a role to grant from the drop-down list. For best security practices,choose a role that includes only the permissions that your principal needs.

  5. Optional: Add acondition to the role.

  6. ClickSave. The principal is granted the role on the resource.

To grant a role to a principal for more than one project, folder, ororganization, do the following:

  1. In the Google Cloud console, go to theManage resources page.

    Go toManage resources

  2. Select all the resources for which you want to grant permissions.

  3. If the info panel is not visible, clickShow info panel. Then, clickPermissions.

  4. Select a principal to grant a role to:

    • To grant a role to a principal who already has other roles, find a rowcontaining the principal, clickEdit principal in that row,and clickAdd another role.
    • To grant a role to a principal who does not already have other roles,clickAdd principal,then enter aprincipalidentifier—for example,my-user@example.com or//iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com.
  5. Select a role to grant from the drop-down list.

  6. Optional: Add acondition to the role.

  7. ClickSave. The principal is granted the selected role on each of theselected resources.

gcloud

Note: To grant the Owner role (roles/owner) on a project to a user outside ofyour organization, you must use the Google Cloud console, not thegcloud CLI. If your project is not part of an organization, you mustuse the Google Cloud console to grant the Owner role.
  1. In the Google Cloud console, activate Cloud Shell.

    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.

  2. Theadd-iam-policy-binding command lets you quickly grant a role to a principal.

    Before using any of the command data below, make the following replacements:

    • RESOURCE_TYPE: The resource type that you want to manage access to. Useprojects,resource-manager folders, ororganizations.

    • RESOURCE_ID: Your Google Cloud project, folder, or organization ID. Project IDs are alphanumeric, likemy-project. Folder and organization IDs are numeric, like123456789012.

    • PRINCIPAL: An identifier for the principal, or member, which usually has the following form:PRINCIPAL_TYPE:ID. For example,user:my-user@example.com orprincipalSet://iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com. For a full list of the values thatPRINCIPAL can have, seePrincipal identifiers.

      For the principal typeuser, the domain name in the identifier must be a Google Workspace domain or a Cloud Identity domain. To learn how to set up a Cloud Identity domain, see theoverview of Cloud Identity.

    • ROLE_NAME: The name of the role that you want to revoke. Use one of the following formats:

      • Predefined roles:roles/SERVICE.IDENTIFIER
      • Project-level custom roles:projects/PROJECT_ID/roles/IDENTIFIER
      • Organization-level custom roles:organizations/ORG_ID/roles/IDENTIFIER

      For a list of predefined roles, seeUnderstanding roles.

    • CONDITION: The condition to add to the role binding. If you don't want to add a condition, use the valueNone. For more information about conditions, see theconditions overview.

    Execute the following command:

    Linux, macOS, or Cloud Shell

    gcloudRESOURCE_TYPEadd-iam-policy-bindingRESOURCE_ID\--member=PRINCIPAL--role=ROLE_NAME\--condition=CONDITION

    Windows (PowerShell)

    gcloudRESOURCE_TYPEadd-iam-policy-bindingRESOURCE_ID`--member=PRINCIPAL--role=ROLE_NAME`--condition=CONDITION

    Windows (cmd.exe)

    gcloudRESOURCE_TYPEadd-iam-policy-bindingRESOURCE_ID^--member=PRINCIPAL--role=ROLE_NAME^--condition=CONDITION

    The response contains the updated IAM policy.

Revoke a single IAM role

To revoke a single role from a principal, do the following:

Console

  1. In the Google Cloud console, go to theIAM page.

    Go to IAM

  2. Select a project, folder, or organization.

  3. Find the row containing the principal whose access you want to revoke. Then,clickEdit principal in thatrow.

    Note: You cannot edit inherited roles when managing access to aresource. To edit inherited roles, go to the resource where therole was granted.
  4. Click theDelete button forthe role that you want to revoke, and then clickSave.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    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.

  2. To quickly revoke a role from a user, run theremove-iam-policy-binding command:

    gcloudRESOURCE_TYPEremove-iam-policy-bindingRESOURCE_ID
    --member=PRINCIPAL--role=ROLE_NAME

    Provide the following values:

    • RESOURCE_TYPE: The resource type that you want to manage access to. Useprojects,resource-manager folders, ororganizations.

    • RESOURCE_ID: Your Google Cloud project, folder, or organization ID. Project IDs are alphanumeric, likemy-project. Folder and organization IDs are numeric, like123456789012.

    • PRINCIPAL: An identifier for the principal, or member, which usually has the following form:PRINCIPAL_TYPE:ID. For example,user:my-user@example.com orprincipalSet://iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com.

      For the principal typeuser, the domain name in the identifier must be a Google Workspace domain or a Cloud Identity domain. To learn how to set up a Cloud Identity domain, see theoverview of Cloud Identity.

    • ROLE_NAME: The name of the role that you want to revoke. Use one of the following formats:

      • Predefined roles:roles/SERVICE.IDENTIFIER
      • Project-level custom roles:projects/PROJECT_ID/roles/IDENTIFIER
      • Organization-level custom roles:organizations/ORG_ID/roles/IDENTIFIER

      For a list of predefined roles, seeUnderstanding roles.

    For example, to revoke the Project Creator role from the service accountexample-service-account@example-project.iam.gserviceaccount.com for the projectexample-project:

    gcloudprojectsremove-iam-policy-bindingexample-project
    --member=serviceAccount:example-service-account@example-project.iam.gserviceaccount.com
    --role=roles/resourcemanager.projectCreator

To help ensure that you don't revoke any necessary roles, you can enablechangerisk recommendations. Change risk recommendationsgenerate warnings when you try to revoke project-level roles thatGoogle Cloud has identified as important.

Grant or revoke multiple IAM roles using the Google Cloud console

You can use the Google Cloud console to grant and revoke multiple roles fora single principal:

  1. In the Google Cloud console, go to theIAM page.

    Go to IAM

  2. Select a project, folder, or organization.

  3. Select the principal whose roles you want to modify:

  4. Modify the principal's roles:

    • To grant a role to a principal who doesn't have any existing roles on theresource, clickSelect a role, then select a role to grant from thedrop-down list.
    • To grant an additional role to the principal, clickAdd another role,then select a role to grant from the drop-down list.
    • To replace one of the principal's roles with a different role, click theexisting role, then choose a different role to grant from the drop-downlist.
    • To revoke one of the principal's roles, click theDelete

    You can alsoadd a condition to a role,modify a role'scondition, orremove a role'scondition.

  5. ClickSave.

Grant or revoke multiple IAM roles programmatically

To make large-scale access changes that involve granting and revoking multipleroles for multiple principals, use theread-modify-write pattern to update theresource's allow policy:

  1. Read the current allow policy by callinggetIamPolicy().
  2. Edit the allow policy, either by using a text editor or programmatically, toadd or remove any principals or role bindings.
  3. Write the updated allow policy by callingsetIamPolicy().

You can use the gcloud CLI, the REST API, or the Resource Managerclient libraries to update the allow policy.

Note: If theiam.allowedPolicyMemberDomains organization policy constraint is enforced in your organization, then you might not be able to grant roles to newly created groups. If you get afailedPrecondition error when trying to grant a role to a newly created group, wait 24 hours, and then try granting the role again.

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.

Get the current allow policy

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    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.

  2. To get the allow policy for the resource, run theget-iam-policy command for the resource:

    gcloudRESOURCE_TYPEget-iam-policyRESOURCE_ID--format=FORMAT >PATH

    Provide the following values:

    • RESOURCE_TYPE: The type of the resource that you want to get the allow policy for. Use one of the following values:projects,resource-manager folders, ororganizations.

    • RESOURCE_ID: Your Google Cloud project, folder, or organization ID. Project IDs are alphanumeric, likemy-project. Folder and organization IDs are numeric, like123456789012.

    • FORMAT: The desired format for the allow policy. Usejson oryaml.

    • PATH: The path to a new output file for the allow policy.

    For example, the following command gets the allow policy for the projectmy-project and saves it to your home directory in JSON format:

    gcloudprojectsget-iam-policymy-project--formatjson >~/policy.json

C#

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

The following example shows how to get the allow policy for a project. To learn how to get the allow policy of a folder or organization, review theResource Managerclient library documentation for your programming language.

usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.CloudResourceManager.v1;usingGoogle.Apis.CloudResourceManager.v1.Data;publicpartialclassAccessManager{publicstaticPolicyGetPolicy(stringprojectId){varcredential=GoogleCredential.GetApplicationDefault().CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);varservice=newCloudResourceManagerService(newCloudResourceManagerService.Initializer{HttpClientInitializer=credential});varpolicy=service.Projects.GetIamPolicy(newGetIamPolicyRequest(),projectId).Execute();returnpolicy;}}

Java

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

The following example shows how to get the allow policy for a project. To learn how to get the allow policy of a folder or organization, review theResource Managerclient library documentation for your programming language.

importcom.google.cloud.resourcemanager.v3.ProjectsClient;importcom.google.iam.admin.v1.ProjectName;importcom.google.iam.v1.GetIamPolicyRequest;importcom.google.iam.v1.Policy;importjava.io.IOException;publicclassGetProjectPolicy{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variables before running the sample.// TODO: Replace with your project ID.StringprojectId="your-project-id";getProjectPolicy(projectId);}// Gets a project's policy.publicstaticPolicygetProjectPolicy(StringprojectId)throwsIOException{// Initialize client that will be used to send requests.// This client only needs to be created once, and can be reused for multiple requests.try(ProjectsClientprojectsClient=ProjectsClient.create()){GetIamPolicyRequestrequest=GetIamPolicyRequest.newBuilder().setResource(ProjectName.of(projectId).toString()).build();returnprojectsClient.getIamPolicy(request);}}}

Python

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

The following example shows how to get the allow policy for a project. To learn how to get the allow policy of a folder or organization, review theResource Managerclient library documentation for your programming language.

fromgoogle.cloudimportresourcemanager_v3fromgoogle.iam.v1importiam_policy_pb2,policy_pb2defget_project_policy(project_id:str)->policy_pb2.Policy:"""Get policy for project.    project_id: ID or number of the Google Cloud project you want to use.    """client=resourcemanager_v3.ProjectsClient()request=iam_policy_pb2.GetIamPolicyRequest()request.resource=f"projects/{project_id}"policy=client.get_iam_policy(request)print(f"Policy retrieved:{policy}")returnpolicy

REST

The Resource Manager API'sgetIamPolicy method gets a project's, folder's, or organization's allow policy.

Before using any of the request data, make the following replacements:

  • API_VERSION: The API version to use. Forprojects and organizations, usev1. For folders, usev2.
  • RESOURCE_TYPE: The resource type whosepolicy you want to manage. Use the valueprojects,folders, ororganizations.
  • RESOURCE_ID: Your Google Cloudproject, organization, or folder ID. Project IDs are alphanumeric strings, likemy-project. Folder and organization IDs are numeric, like123456789012.
  • POLICY_VERSION: The policy version to bereturned. Requests should specify the most recent policy version, which is policy version3. SeeSpecifyinga policy version when getting a policy for details.

HTTP method and URL:

POST https://cloudresourcemanager.googleapis.com/API_VERSION/RESOURCE_TYPE/RESOURCE_ID:getIamPolicy

Request JSON body:

{  "options": {    "requestedPolicyVersion":POLICY_VERSION  }}

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://cloudresourcemanager.googleapis.com/API_VERSION/RESOURCE_TYPE/RESOURCE_ID:getIamPolicy"

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://cloudresourcemanager.googleapis.com/API_VERSION/RESOURCE_TYPE/RESOURCE_ID:getIamPolicy" | 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.

The response contains the resource's allow policy. For example:

{  "version": 1,  "etag": "BwWKmjvelug=",  "bindings": [    {      "role": "roles/owner",      "members": [        "user:my-user@example.com"      ]    }  ]}

Save the response in a file of the appropriate type (json oryaml).

Modify the allow policy

Programmatically or using a text editor, modify the local copy of yourresource's allow policy to reflect the roles that you want to grant or revoke.

To help prevent you from overwriting other changes, don't edit or remove theallow policy'setag field. Theetag field identifies the current state ofthe allow policy. When youset the updated allow policy,IAM compares theetag value in the request with theexistingetag, and only writes the allow policy if the values match.

Important: None of your changes will take effect until youset the updated allow policy.

To edit the roles that an allow policy grants, you need to edit the rolebindings in the allow policy. Role bindings have the following format:

{"role":"ROLE_NAME","members":["PRINCIPAL_1","PRINCIPAL_2",..."PRINCIPAL_N"],"conditions:"{CONDITIONS}}

The placeholders have the following values:

  • ROLE_NAME: The name of the role that you want togrant. Use one of the following formats:

    • Predefined roles:roles/SERVICE.IDENTIFIER
    • Project-level custom roles:projects/PROJECT_ID/roles/IDENTIFIER
    • Organization-level custom roles:organizations/ORG_ID/roles/IDENTIFIER

    For a list of predefined roles, seeUnderstandingroles.

  • PRINCIPAL_1,PRINCIPAL_2,...PRINCIPAL_N: Identifiers for the principals thatyou want to grant the role to.

    Principal identifiers usually have the following form:PRINCIPAL-TYPE:ID.For example,user:my-user@example.com orprincipalSet://iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com.For a full list of the values thatPRINCIPAL can have,seePrincipal identifiers.

    For the principal typeuser, the domain name in the identifier must bea Google Workspace domain or a Cloud Identity domain. To learn how to setup a Cloud Identity domain, see theoverview of Cloud Identity.

  • CONDITIONS: Optional. Anyconditionsthat specify when access will be granted.

Grant an IAM role

To grant roles to your principals, modify the role bindings in the allow policy.To learn what roles you can grant, seeUnderstanding roles, orview grantable roles for the resource. If you need help toidentify the most appropriate predefined roles, seeFind the right predefined roles.

Optionally, you can useconditions to grant roles only whencertain requirements are met.

To grant a role that is already included in the allow policy, add the principalto an existing role binding:

gcloud

Edit the returned allow policy by adding the principal to an existing rolebinding. This change won't take effect until youset the updated allow policy.

For example, imagine the allow policy contains the following role binding, whichgrants the Security Reviewer role (roles/iam.securityReviewer) toKai:

{"role":"roles/iam.securityReviewer","members":["user:kai@example.com"]}

To grant that same role to Raha, add Raha's principal identifier to theexisting role binding:

{"role":"roles/iam.securityReviewer","members":["user:kai@example.com","user:raha@example.com"]}

C#

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

usingSystem.Linq;usingGoogle.Apis.CloudResourceManager.v1.Data;publicpartialclassAccessManager{publicstaticPolicyAddMember(Policypolicy,stringrole,stringmember){varbinding=policy.Bindings.First(x=>x.Role==role);binding.Members.Add(member);returnpolicy;}}

Go

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

import("fmt""io""google.golang.org/api/iam/v1")// addMember adds a member to a role binding.funcaddMember(wio.Writer,policy*iam.Policy,role,memberstring){for_,binding:=rangepolicy.Bindings{ifbinding.Role!=role{continue}for_,m:=rangebinding.Members{ifm!=member{continue}fmt.Fprintf(w,"Role %q found. Member already exists.\n",role)return}binding.Members=append(binding.Members,member)fmt.Fprintf(w,"Role %q found. Member added.\n",role)return}fmt.Fprintf(w,"Role %q not found. Member not added.\n",role)}

Java

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

importcom.google.iam.v1.Binding;importcom.google.iam.v1.Policy;importjava.util.ArrayList;importjava.util.List;publicclassAddMember{publicstaticvoidmain(String[]args){// TODO(developer): Replace the variables before running the sample.// TODO: Replace with your policy, GetPolicy.getPolicy(projectId, serviceAccount).Policypolicy=Policy.newBuilder().build();// TODO: Replace with your role.Stringrole="roles/existing-role";// TODO: Replace with your principal.// For examples, see https://cloud.google.com/iam/docs/principal-identifiersStringmember="principal-id";addMember(policy,role,member);}// Adds a principal to a pre-existing role.publicstaticPolicyaddMember(Policypolicy,Stringrole,Stringmember){List<Binding>newBindingsList=newArrayList<>();for(Bindingb:policy.getBindingsList()){if(b.getRole().equals(role)){newBindingsList.add(b.toBuilder().addMembers(member).build());}else{newBindingsList.add(b);}}// Update the policy to add the principal.PolicyupdatedPolicy=policy.toBuilder().clearBindings().addAllBindings(newBindingsList).build();System.out.println("Added principal: "+updatedPolicy.getBindingsList());returnupdatedPolicy;}}

Python

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

fromgoogle.iam.v1importpolicy_pb2fromsnippets.get_policyimportget_project_policyfromsnippets.set_policyimportset_project_policydefmodify_policy_add_principal(project_id:str,role:str,principal:str)->policy_pb2.Policy:"""Add a principal to certain role in project policy.    project_id: ID or number of the Google Cloud project you want to use.    role: role to which principal need to be added.    principal: The principal requesting access.    For principal ID formats, see https://cloud.google.com/iam/docs/principal-identifiers    """policy=get_project_policy(project_id)forbindinpolicy.bindings:ifbind.role==role:bind.members.append(principal)breakreturnset_project_policy(project_id,policy)

REST

Edit the returned allow policy by adding the principal to an existing rolebinding. This change won't take effect until youset the updated allow policy.

For example, imagine the allow policy contains the following role binding, whichgrants the Security Reviewer role (roles/iam.securityReviewer) toKai:

{"role":"roles/iam.securityReviewer","members":["user:kai@example.com"]}

To grant that same role to Raha, add Raha's principal identifier to theexisting role binding:

{"role":"roles/iam.securityReviewer","members":["user:kai@example.com","user:raha@example.com"]}

To grant a role that is not yet included in the allow policy, add a new rolebinding:

gcloud

Edit the allow policy by adding a new role binding that grants the role to theprincipal. This change won't take effect until youset the updated allow policy.

For example, to grant the Compute Storage Admin role(roles/compute.storageAdmin) to Raha, add the following role binding to thebindings array for the allow policy:

{"role":"roles/compute.storageAdmin","members":["user:raha@example.com"]}

C#

To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC# API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

usingSystem.Collections.Generic;usingGoogle.Apis.CloudResourceManager.v1.Data;publicpartialclassAccessManager{publicstaticPolicyAddBinding(Policypolicy,stringrole,stringmember){varbinding=newBinding{Role=role,Members=newList<string>{member}};policy.Bindings.Add(binding);returnpolicy;}}

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.

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

importcom.google.iam.v1.Binding;importcom.google.iam.v1.Policy;importjava.util.Collections;importjava.util.List;publicclassAddBinding{publicstaticvoidmain(String[]args){// TODO(developer): Replace the variables before running the sample.// TODO: Replace with your policy: GetPolicy.getPolicy(projectId, serviceAccount).Policypolicy=Policy.newBuilder().build();// TODO: Replace with your role.Stringrole="roles/role-to-add";// TODO: Replace with your principals.// For examples, see https://cloud.google.com/iam/docs/principal-identifiersList<String>members=Collections.singletonList("principal-id");addBinding(policy,role,members);}// Adds a principals to a role.publicstaticPolicyaddBinding(Policypolicy,Stringrole,List<String>members){Bindingbinding=Binding.newBuilder().setRole(role).addAllMembers(members).build();// Update bindings for the policy.PolicyupdatedPolicy=policy.toBuilder().addBindings(binding).build();System.out.println("Added binding: "+updatedPolicy.getBindingsList());returnupdatedPolicy;}}

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.

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

defmodify_policy_add_role(policy:dict,role:str,principal:str)->dict:"""Adds a new role binding to a policy."""binding={"role":role,"members":[principal]}policy["bindings"].append(binding)print(policy)returnpolicy

REST

Edit the allow policy by adding a new role binding that grants the role to theprincipal. This change won't take effect until youset the updated allow policy.

For example, to grant the Compute Storage Admin role(roles/compute.storageAdmin) to Raha, add the following role binding to thebindings array for the allow policy:

{"role":"roles/compute.storageAdmin","members":["user:raha@example.com"]}

You can only grant roles related to activated API services. If a service, suchas Compute Engine, is not active, you cannot grant roles exclusively related toCompute Engine. For more information, seeEnable and disable APIs.

There are some unique constraints when granting permissions on projects,especially when granting the Owner (roles/owner) role. See theprojects.setIamPolicy()reference documentationfor more information.

Revoke an IAM role

To revoke a role, remove the principal from the role binding. If there are noother principals in the role binding, remove the entire role binding.

Note: Role bindings with no principals are not allowed and will result in anerror when setting the allow policy.

gcloud

Revoke a role by editing the JSON or YAML allow policy returned by theget-iam-policy command. This change won't take effect until youset the updated allow policy.

To revoke a role from a principal, delete the principal or binding from thebindings array for the allow policy.

C#

To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC# API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

usingSystem.Linq;usingGoogle.Apis.CloudResourceManager.v1.Data;publicpartialclassAccessManager{publicstaticPolicyRemoveMember(Policypolicy,stringrole,stringmember){try{varbinding=policy.Bindings.First(x=>x.Role==role);if(binding.Members.Count!=0 &&binding.Members.Contains(member)){binding.Members.Remove(member);}if(binding.Members.Count==0){policy.Bindings.Remove(binding);}returnpolicy;}catch(System.InvalidOperationExceptione){System.Diagnostics.Debug.WriteLine("Role does not exist in policy: \n"+e.ToString());returnpolicy;}}}

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.

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

import("fmt""io""google.golang.org/api/iam/v1")// removeMember removes a member from a role binding.funcremoveMember(wio.Writer,policy*iam.Policy,role,memberstring){bindings:=policy.BindingsbindingIndex,memberIndex:=-1,-1forbIdx:=rangebindings{ifbindings[bIdx].Role!=role{continue}bindingIndex=bIdxformIdx:=rangebindings[bindingIndex].Members{ifbindings[bindingIndex].Members[mIdx]!=member{continue}memberIndex=mIdxbreak}}ifbindingIndex==-1{fmt.Fprintf(w,"Role %q not found. Member not removed.\n",role)return}ifmemberIndex==-1{fmt.Fprintf(w,"Role %q found. Member not found.\n",role)return}members:=removeIdx(bindings[bindingIndex].Members,memberIndex)bindings[bindingIndex].Members=membersiflen(members)==0{bindings=removeIdx(bindings,bindingIndex)policy.Bindings=bindings}fmt.Fprintf(w,"Role %q found. Member removed.\n",role)}// removeIdx removes arr[idx] from arr.funcremoveIdx[Tany](arr[]T,idxint)[]T{returnappend(arr[:idx],arr[idx+1:]...)}

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.

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

importcom.google.iam.v1.Binding;importcom.google.iam.v1.Policy;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;publicclassRemoveMember{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variables before running the sample.// TODO: Replace with your policy, GetPolicy.getPolicy(projectId, serviceAccount).Policypolicy=Policy.newBuilder().build();// TODO: Replace with your role.Stringrole="roles/existing-role";// TODO: Replace with your principal.// For examples, see https://cloud.google.com/iam/docs/principal-identifiersStringmember="principal-id";removeMember(policy,role,member);}// Removes principal from a role; removes binding if binding contains no members.publicstaticPolicyremoveMember(Policypolicy,Stringrole,Stringmember){// Creating new builder with all values copied from origin policyPolicy.BuilderpolicyBuilder=policy.toBuilder();// Getting binding with suitable role.Bindingbinding=null;for(Bindingb:policy.getBindingsList()){if(b.getRole().equals(role)){binding=b;break;}}if(binding!=null &&binding.getMembersList().contains(member)){List<String>newMemberList=newArrayList<>(binding.getMembersList());// Removing principal from the rolenewMemberList.remove(member);System.out.println("Member "+member+" removed from "+role);// Adding all remaining principals to create new bindingBindingnewBinding=binding.toBuilder().clearMembers().addAllMembers(newMemberList).build();List<Binding>newBindingList=newArrayList<>(policyBuilder.getBindingsList());// Removing old binding to replace with new onenewBindingList.remove(binding);// If binding has no more members, binding will not be addedif(!newBinding.getMembersList().isEmpty()){newBindingList.add(newBinding);}// Update the policy to remove the principal.policyBuilder.clearBindings().addAllBindings(newBindingList);}PolicyupdatedPolicy=policyBuilder.build();System.out.println("Exising principals: "+updatedPolicy.getBindingsList());returnupdatedPolicy;}}

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.

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

fromgoogle.iam.v1importpolicy_pb2fromsnippets.get_policyimportget_project_policyfromsnippets.set_policyimportset_project_policydefmodify_policy_remove_principal(project_id:str,role:str,principal:str)->policy_pb2.Policy:"""Remove a principal from certain role in project policy.    project_id: ID or number of the Google Cloud project you want to use.    role: role to revoke.    principal: The principal to revoke access from.    For principal ID formats, see https://cloud.google.com/iam/docs/principal-identifiers    """policy=get_project_policy(project_id)forbindinpolicy.bindings:ifbind.role==role:ifprincipalinbind.members:bind.members.remove(principal)breakreturnset_project_policy(project_id,policy,False)

REST

Revoke a role by editing the JSON or YAML allow policy returned by theget-iam-policy command. This change won't take effect until youset the updated allow policy.

To revoke a role from a principal, delete the principal or binding from thebindings array for the allow policy.

Set the allow policy

After you modify the allow policy to grant and revoke roles, callsetIamPolicy() to update the policy.

Warning: Setting a new allow policy permanently overwrites the existing allowpolicy on the resource. To avoid removing role bindings unintentionally, alwaysfollow the read-modify-write pattern when updating an allow policy: read theexisting allow policy, modify it as needed, and then write the updated versionof the allow policy.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    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.

  2. To set the allow policy for the resource, run theset-iam-policy command for the resource:

    gcloudRESOURCE_TYPEset-iam-policyRESOURCE_IDPATH

    Provide the following values:

    • RESOURCE_TYPE: The type of the resource that you want to set the allow policy for. Use one of the following values:projects,resource-manager folders, ororganizations.

    • RESOURCE_ID: Your Google Cloud project, folder, or organization ID. Project IDs are alphanumeric, likemy-project. Folder and organization IDs are numeric, like123456789012.

    • PATH: The path to a file that contains the new allow policy.

    The response contains the updated allow policy.

    For example, the following command sets the allow policy stored inpolicy.json as the allow policy for the projectmy-project:

    gcloudprojectsset-iam-policymy-project~/policy.json

Note: If you treat policies as code and store them in a version-control system, you should store the policy that is returned, not the policy that you sent in the request.

C#

usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.CloudResourceManager.v1;usingGoogle.Apis.CloudResourceManager.v1.Data;publicpartialclassAccessManager{publicstaticPolicySetPolicy(stringprojectId,Policypolicy){varcredential=GoogleCredential.GetApplicationDefault().CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);varservice=newCloudResourceManagerService(newCloudResourceManagerService.Initializer{HttpClientInitializer=credential});returnservice.Projects.SetIamPolicy(newSetIamPolicyRequest{Policy=policy},projectId).Execute();}}

Java

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

The following example shows how to set the allow policy for a project. To learn how to set the allow policy of a folder or organization, review theResource Manager client library documentation for your programming language.

importcom.google.cloud.resourcemanager.v3.ProjectsClient;importcom.google.iam.admin.v1.ProjectName;importcom.google.iam.v1.Policy;importcom.google.iam.v1.SetIamPolicyRequest;importcom.google.protobuf.FieldMask;importjava.io.IOException;importjava.util.Arrays;importjava.util.List;publicclassSetProjectPolicy{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variables before running the sample.// TODO: Replace with your project ID.StringprojectId="your-project-id";// TODO: Replace with your policy, GetPolicy.getPolicy(projectId, serviceAccount).Policypolicy=Policy.newBuilder().build();setProjectPolicy(policy,projectId);}// Sets a project's policy.publicstaticPolicysetProjectPolicy(Policypolicy,StringprojectId)throwsIOException{// Initialize client that will be used to send requests.// This client only needs to be created once, and can be reused for multiple requests.try(ProjectsClientprojectsClient=ProjectsClient.create()){List<String>paths=Arrays.asList("bindings","etag");SetIamPolicyRequestrequest=SetIamPolicyRequest.newBuilder().setResource(ProjectName.of(projectId).toString()).setPolicy(policy)// A FieldMask specifying which fields of the policy to modify. Only// the fields in the mask will be modified. If no mask is provided, the// following default mask is used:// `paths: "bindings, etag"`.setUpdateMask(FieldMask.newBuilder().addAllPaths(paths).build()).build();returnprojectsClient.setIamPolicy(request);}}}

Python

To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.

To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.

The following example shows how to set the allow policy for a project. To learn how to set the allow policy of a folder or organization, review theResource Manager client library documentation for your programming language.

fromgoogle.cloudimportresourcemanager_v3fromgoogle.iam.v1importiam_policy_pb2,policy_pb2defset_project_policy(project_id:str,policy:policy_pb2.Policy,merge:bool=True)->policy_pb2.Policy:"""    Set policy for project. Pay attention that previous state will be completely rewritten.    If you want to update only part of the policy follow the approach read->modify->write.    For more details about policies check out https://cloud.google.com/iam/docs/policies    project_id: ID or number of the Google Cloud project you want to use.    policy: Policy which has to be set.    merge: The strategy to be used forming the request. CopyFrom is clearing both mutable and immutable fields,    when MergeFrom is replacing only immutable fields and extending mutable.    https://googleapis.dev/python/protobuf/latest/google/protobuf/message.html#google.protobuf.message.Message.CopyFrom    """client=resourcemanager_v3.ProjectsClient()request=iam_policy_pb2.GetIamPolicyRequest()request.resource=f"projects/{project_id}"current_policy=client.get_iam_policy(request)# Etag should as fresh as possible to lower chance of collisionspolicy.ClearField("etag")ifmerge:current_policy.MergeFrom(policy)else:current_policy.CopyFrom(policy)request=iam_policy_pb2.SetIamPolicyRequest()request.resource=f"projects/{project_id}"# request.etag field also will be merged which means you are secured from collision,# but it means that request may fail and you need to leverage exponential retries approach# to be sure policy has been updated.request.policy.CopyFrom(current_policy)policy=client.set_iam_policy(request)returnpolicy

REST

The Resource Manager API'ssetIamPolicy method sets the policy in the request as the new allow policy for the project, folder, or organization.

Before using any of the request data, make the following replacements:

  • API_VERSION: The API version to use. Forprojects and organizations, usev1. For folders, usev2.
  • RESOURCE_TYPE: The resource type whosepolicy you want to manage. Use the valueprojects,folders, ororganizations.
  • RESOURCE_ID: Your Google Cloudproject, organization, or folder ID. Project IDs are alphanumeric strings, likemy-project. Folder and organization IDs are numeric, like123456789012.
  • POLICY: A JSON representation of the policy that youwant to set. For more information about the format of a policy, see thePolicy reference.

HTTP method and URL:

POST https://cloudresourcemanager.googleapis.com/API_VERSION/RESOURCE_TYPE/RESOURCE_ID:setIamPolicy

Request JSON body:

{  "policy":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 POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://cloudresourcemanager.googleapis.com/API_VERSION/RESOURCE_TYPE/RESOURCE_ID:setIamPolicy"

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://cloudresourcemanager.googleapis.com/API_VERSION/RESOURCE_TYPE/RESOURCE_ID:setIamPolicy" | 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.

The response contains the updated allow policy.

Note: If you treat policies as code and store them in a version-control system, you should store the policy that is returned, not the policy that you sent in the request.

What's next

Try it for yourself

If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.

Get started for free

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-07-02 UTC.