Manage access to projects, folders, and organizations

Stay organized with collections Save and categorize content based on your preferences.

This page describes how to grant, change, and revoke access to projects, folders, and organizations. To learn how to manage access to other resources, see the following guides:

In Identity and Access Management (IAM), access is granted through allow policies, also known as IAM policies. An allow policy is attached to a Google Cloud resource. Each allow policy contains a collection of role bindings that associate one or more principals, such as users or service accounts, with an IAM role. These role bindings grant the specified roles to the principals, both on the resource that the allow policy is attached to and on all of that resource's descendants. For more information about allow policies, see Understanding allow policies.

You can manage access to projects, folders, and organizations with the Google Cloud console, the Google Cloud CLI, the REST API, or the Resource Manager client libraries.

Before you begin

  • Enable the Resource Manager API.

    Enable the API

Required roles

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)

For more information about granting roles, see Manage access.

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 the Required permissions section:

Required permissions

  • 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 with custom roles or other predefined roles.

View current access

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

Console

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

    Go to IAM

  2. Select a project, folder, or organization.

    The Google Cloud console lists all the principals who have been granted roles on your project, folder, or organization. This list includes principals who have inherited roles on the resource from parent resources. For more information about policy inheritance, see Policy inheritance and the resource hierarchy.

  3. Optional: To view role grants for Google-managed service accounts, select the Include Google-provided role grants checkbox.

gcloud CLI

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, see Understanding allow policies.

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

gcloud RESOURCE_TYPE get-iam-policy RESOURCE_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, or organizations.
  • RESOURCE_ID: Your Google Cloud project, folder, or organization ID. Project IDs are alphanumeric, like my-project. Folder and organization IDs are numeric, like 123456789012.
  • FORMAT: The desired format for the policy. Use json or yaml.
  • PATH: The path to a new output file for the policy.

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

gcloud projects get-iam-policy my-project --format=json > ~/policy.json

REST

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, see Understanding allow policies.

The Resource Manager API's getIamPolicy 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. For projects and organizations, use v1. For folders, use v2.
  • RESOURCE_TYPE: The resource type whose policy you want to manage. Use the value projects, folders, or organizations.
  • RESOURCE_ID: Your Google Cloud project, organization, or folder ID. Project IDs are alphanumeric strings, like my-project. Folder and organization IDs are numeric, like 123456789012.
  • POLICY_VERSION: The policy version to be returned. Requests should specify the most recent policy version, which is policy version 3. See Specifying a 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:

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

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

C#


using Google.Apis.Auth.OAuth2;
using Google.Apis.CloudResourceManager.v1;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy GetPolicy(string projectId)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);
        var service = new CloudResourceManagerService(
            new CloudResourceManagerService.Initializer
            {
                HttpClientInitializer = credential
            });

        var policy = service.Projects.GetIamPolicy(new GetIamPolicyRequest(),
            projectId).Execute();
        return policy;
    }
}

Java

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.cloudresourcemanager.v3.CloudResourceManager;
import com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest;
import com.google.api.services.cloudresourcemanager.v3.model.Policy;
import com.google.api.services.iam.v1.IamScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class GetPolicy {

  // Gets a project's policy.
  public static Policy getPolicy(String projectId) {
    // projectId = "my-project-id"

    Policy policy = null;

    CloudResourceManager service = null;
    try {
      service = createCloudResourceManagerService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e.toString());
      return policy;
    }

    try {
      GetIamPolicyRequest request = new GetIamPolicyRequest();
      policy = service.projects().getIamPolicy(projectId, request).execute();
      System.out.println("Policy retrieved: " + policy.toString());
      return policy;
    } catch (IOException e) {
      System.out.println("Unable to get policy: \n" + e.toString());
      return policy;
    }
  }

  public static CloudResourceManager createCloudResourceManagerService()
      throws IOException, GeneralSecurityException {
    // Use the Application Default Credentials strategy for authentication. For more info, see:
    // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

    CloudResourceManager service =
        new CloudResourceManager.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

def get_policy(project_id, version=1):
    """Gets IAM policy for a project."""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )
    service = googleapiclient.discovery.build(
        "cloudresourcemanager", "v1", credentials=credentials
    )
    policy = (
        service.projects()
        .getIamPolicy(
            resource=project_id,
            body={"options": {"requestedPolicyVersion": version}},
        )
        .execute()
    )
    print(policy)
    return policy

Grant or revoke a single role

You can use the Google Cloud console and the gcloud CLI to quickly grant or revoke a single role for a single principal, without editing the resource's allow policy directly. Common types of principals include Google accounts, service accounts, Google groups, and domains. For a list of all principal types, see Concepts related to identity.

If you need help identifying the most appropriate predefined role, see Choose predefined roles.

Grant a single role

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

Console

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

    Go to IAM

  2. Select a project, folder, or organization.

  3. Select a principal to grant a role to:

    • To grant a role to a principal who already has other roles on the resource, find a row containing the principal, click Edit principal in that row, and click Add another role.

      To grant a role to a Google-managed service account, select the Include Google-provided role grants checkbox to see its email address.

    • To grant a role to a principal who does not already have other roles on the resource, click Grant Access, then enter the principal's email address or other identifier.

  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 a condition to the role.

  6. Click Save. The principal is granted the role on the resource.

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

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

    Go to Manage resources

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

  3. If the info panel is not visible, click Show info panel. Then, click Permissions.

  4. Select a principal to grant a role to:

    • To grant a role to a principal who already has other roles, find a row containing the principal, click Edit principal in that row, and click Add another role.

    • To grant a role to a principal who does not already have other roles, click Add principal, then enter the principal's email address or other identifier.

  5. Select a role to grant from the drop-down list.

  6. Optional: Add a condition to the role.

  7. Click Save. The principal is granted the selected role on each of the selected resources.

gcloud CLI

To quickly grant a role to a principal, run the add-iam-policy-binding command:

gcloud RESOURCE_TYPE add-iam-policy-binding RESOURCE_ID \
    --member=PRINCIPAL --role=ROLE_ID \
    --condition=CONDITION

Provide the following values:

  • RESOURCE_TYPE: The resource type that you want to manage access to. Use projects, resource-manager folders, or organizations.
  • RESOURCE_ID: Your Google Cloud project, folder, or organization ID. Project IDs are alphanumeric, like my-project. Folder and organization IDs are numeric, like 123456789012.
  • PRINCIPAL: An identifier for the principal, or member, which usually has the following form: PRINCIPAL_TYPE:ID. For example, user:my-user@example.com. For a full list of the values that PRINCIPAL can have, see the Policy Binding reference.

    For the principal type user, 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 the overview of Cloud Identity.

  • ROLE_ID: The name of the role that you want to grant. For example, roles/resourcemanager.projectCreator. For a list of roles, see Understanding roles.

  • CONDITION: Optional. The condition to add to the role binding. For more information about conditions, see the conditions overview.

For example, to grant the Project Creator role to the user my-user@example.com for the project my-project:

gcloud projects add-iam-policy-binding my-project \
    --member=user:my-user@example.com --role=roles/resourcemanager.projectCreator

Revoke a single role

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

Console

  1. In the Google Cloud console, go to the IAM 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, click Edit principal in that row.

  4. Click the Delete button for each role you want to revoke, and then click Save.

gcloud CLI

To quickly revoke a role from a user, run the remove-iam-policy-binding command:

gcloud RESOURCE_TYPE remove-iam-policy-binding RESOURCE_ID \
    --member=PRINCIPAL --role=ROLE_ID

Provide the following values:

  • RESOURCE_TYPE: The resource type that you want to manage access to. Use projects, resource-manager folders, or organizations.
  • RESOURCE_ID: Your Google Cloud project, folder, or organization ID. Project IDs are alphanumeric, like my-project. Folder and organization IDs are numeric, like 123456789012.
  • PRINCIPAL: An identifier for the principal, or member, which usually has the following form: PRINCIPAL_TYPE:ID. For example, user:my-user@example.com. For a full list of the values that PRINCIPAL can have, see the Policy Binding reference.

    For the principal type user, 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 the overview of Cloud Identity.

  • ROLE_ID: The name of the role that you want to revoke. For example, roles/resourcemanager.projectCreator. For a list of roles, see Understanding roles.

For example, to revoke the Project Creator role from the user my-user@example.com for the project my-project:

gcloud projects remove-iam-policy-binding my-project \
    --member=user:my-user@example.com --role=roles/resourcemanager.projectCreator

Grant or revoke multiple roles

To make large-scale access changes that involve granting and revoking multiple roles, use the read-modify-write pattern to update the resource's allow policy:

  1. Read the current allow policy by calling getIamPolicy().
  2. Edit the allow policy, either by using a text editor or programmatically, to add or remove any principals or role bindings.
  3. Write the updated allow policy by calling setIamPolicy().

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

Get the current allow policy

gcloud CLI

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

gcloud RESOURCE_TYPE get-iam-policy RESOURCE_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, or organizations.
  • RESOURCE_ID: Your Google Cloud project, folder, or organization ID. Project IDs are alphanumeric, like my-project. Folder and organization IDs are numeric, like 123456789012.
  • FORMAT: The desired format for the allow policy. Use json or yaml.
  • PATH: The path to a new output file for the allow policy.

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

gcloud projects get-iam-policy my-project --format json > ~/policy.json

REST

The Resource Manager API's getIamPolicy 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. For projects and organizations, use v1. For folders, use v2.
  • RESOURCE_TYPE: The resource type whose policy you want to manage. Use the value projects, folders, or organizations.
  • RESOURCE_ID: Your Google Cloud project, organization, or folder ID. Project IDs are alphanumeric strings, like my-project. Folder and organization IDs are numeric, like 123456789012.
  • POLICY_VERSION: The policy version to be returned. Requests should specify the most recent policy version, which is policy version 3. See Specifying a 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:

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

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

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

C#


using Google.Apis.Auth.OAuth2;
using Google.Apis.CloudResourceManager.v1;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy GetPolicy(string projectId)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);
        var service = new CloudResourceManagerService(
            new CloudResourceManagerService.Initializer
            {
                HttpClientInitializer = credential
            });

        var policy = service.Projects.GetIamPolicy(new GetIamPolicyRequest(),
            projectId).Execute();
        return policy;
    }
}

Java

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.cloudresourcemanager.v3.CloudResourceManager;
import com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest;
import com.google.api.services.cloudresourcemanager.v3.model.Policy;
import com.google.api.services.iam.v1.IamScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class GetPolicy {

  // Gets a project's policy.
  public static Policy getPolicy(String projectId) {
    // projectId = "my-project-id"

    Policy policy = null;

    CloudResourceManager service = null;
    try {
      service = createCloudResourceManagerService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e.toString());
      return policy;
    }

    try {
      GetIamPolicyRequest request = new GetIamPolicyRequest();
      policy = service.projects().getIamPolicy(projectId, request).execute();
      System.out.println("Policy retrieved: " + policy.toString());
      return policy;
    } catch (IOException e) {
      System.out.println("Unable to get policy: \n" + e.toString());
      return policy;
    }
  }

  public static CloudResourceManager createCloudResourceManagerService()
      throws IOException, GeneralSecurityException {
    // Use the Application Default Credentials strategy for authentication. For more info, see:
    // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

    CloudResourceManager service =
        new CloudResourceManager.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

def get_policy(project_id, version=1):
    """Gets IAM policy for a project."""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )
    service = googleapiclient.discovery.build(
        "cloudresourcemanager", "v1", credentials=credentials
    )
    policy = (
        service.projects()
        .getIamPolicy(
            resource=project_id,
            body={"options": {"requestedPolicyVersion": version}},
        )
        .execute()
    )
    print(policy)
    return policy

Modify the allow policy

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

To ensure that you do not overwrite other changes, do not edit or remove the allow policy's etag field. The etag field identifies the current state of the allow policy. When you set the updated allow policy, IAM compares the etag value in the request with the existing etag, and only writes the allow policy if the values match.

Grant a role

To grant roles to your principals, modify the role bindings in the allow policy. To learn what roles you can grant, see Understanding roles, or view grantable roles for the resource. If you need help to identify the most appropriate predefined roles, see Choose predefined roles.

Optionally, you can use conditions to grant roles only when certain requirements are met.

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

gcloud CLI

Edit the returned allow policy by adding the principal to an existing role binding. Note that this change will not take effect until you set the updated allow policy.

For example, imagine the allow policy contains the following role binding, which grants the Security Reviewer role (roles/iam.securityReviewer) to kai@example.com:

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

To grant that same role to raha@example.com, add raha@example.com to the existing role binding:

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

REST

Edit the returned allow policy by adding the principal to an existing role binding. Note that this change will not take effect until you set the updated allow policy.

For example, imagine the allow policy contains the following role binding, which grants the Security Reviewer role (roles/iam.securityReviewer) to kai@example.com:

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

To grant that same role to raha@example.com, add raha@example.com to the existing role binding:

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

C#

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


using System.Linq;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy AddMember(Policy policy, string role, string member)
    {
        var binding = policy.Bindings.First(x => x.Role == role);
        binding.Members.Add(member);
        return policy;
    }
}

Java

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

import com.google.api.services.cloudresourcemanager.v3.model.Binding;
import com.google.api.services.cloudresourcemanager.v3.model.Policy;
import java.util.List;

public class AddMember {

  // Adds a member to a preexisting role.
  public static void addMember(Policy policy) {
    // policy = service.Projects.GetIAmPolicy(new GetIamPolicyRequest(), your-project-id).Execute();

    String role = "roles/existing-role";
    String member = "user:member-to-add@example.com";

    List<Binding> bindings = policy.getBindings();

    for (Binding b : bindings) {
      if (b.getRole().equals(role)) {
        b.getMembers().add(member);
        System.out.println("Member " + member + " added to role " + role);
        return;
      }
    }

    System.out.println("Role not found in policy; member not added");
  }
}

Python

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

def modify_policy_add_member(policy, role, member):
    """Adds a new member to a role binding."""

    binding = next(b for b in policy["bindings"] if b["role"] == role)
    binding["members"].append(member)
    print(binding)
    return policy

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

gcloud CLI

Edit the allow policy by adding a new role binding that grants the role to the principal. This change will not take effect until you set the updated allow policy.

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

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

REST

Edit the allow policy by adding a new role binding that grants the role to the principal. This change will not take effect until you set the updated allow policy.

For example, to grant the Compute Storage Admin role (roles/compute.storageAdmin) to raha@example.com, add the following role binding to the bindings 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 Resource Manager, see Resource Manager client libraries.


using System.Collections.Generic;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy AddBinding(Policy policy, string role, string member)
    {
        var binding = new Binding
        {
            Role = role,
            Members = new List<string> { member }
        };
        policy.Bindings.Add(binding);
        return policy;
    }
}

Java

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

import com.google.api.services.cloudresourcemanager.v3.model.Binding;
import com.google.api.services.cloudresourcemanager.v3.model.Policy;
import java.util.ArrayList;
import java.util.List;

public class AddBinding {

  // Adds a member to a role with no previous members.
  public static void addBinding(Policy policy) {
    // policy = service.Projects.GetIAmPolicy(new GetIamPolicyRequest(), your-project-id).Execute();

    String role = "roles/role-to-add";
    List<String> members = new ArrayList<String>();
    members.add("user:member-to-add@example.com");

    Binding binding = new Binding();
    binding.setRole(role);
    binding.setMembers(members);

    policy.getBindings().add(binding);
    System.out.println("Added binding: " + binding.toString());
  }
}

Python

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

def modify_policy_add_role(policy, role, member):
    """Adds a new role binding to a policy."""

    binding = {"role": role, "members": [member]}
    policy["bindings"].append(binding)
    print(policy)
    return policy

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

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

Revoke a role

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

gcloud CLI

Revoke a role by editing the JSON or YAML allow policy returned by the get-iam-policy command. This change will not take effect until you set the updated allow policy.

To revoke a role from a principal, delete the desired principals or bindings from the bindings array for the allow policy.

REST

Revoke a role by editing the JSON or YAML allow policy returned by the get-iam-policy command. This change will not take effect until you set the updated allow policy.

To revoke a role from a principal, delete the desired principals or bindings from the bindings array for the allow policy.

C#

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


using System.Linq;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy RemoveMember(Policy policy, string role, string member)
    {
        try
        {
            var binding = 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);
            }
            return policy;
        }
        catch (System.InvalidOperationException e)
        {
            System.Diagnostics.Debug.WriteLine("Role does not exist in policy: \n" + e.ToString());
            return policy;
        }
    }
}

Java

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

import com.google.api.services.cloudresourcemanager.v3.model.Binding;
import com.google.api.services.cloudresourcemanager.v3.model.Policy;
import java.util.List;

public class RemoveMember {

  // Removes member from a role; removes binding if binding contains 0 members.
  public static void removeMember(Policy policy) {
    // policy = service.Projects.GetIAmPolicy(new GetIamPolicyRequest(), your-project-id).Execute();

    String role = "roles/existing-role";
    String member = "user:member-to-remove@example.com";

    List<Binding> bindings = policy.getBindings();
    Binding binding = null;
    for (Binding b : bindings) {
      if (b.getRole().equals(role)) {
        binding = b;
      }
    }
    if (binding.getMembers().contains(member)) {
      binding.getMembers().remove(member);
      System.out.println("Member " + member + " removed from " + role);
      if (binding.getMembers().isEmpty()) {
        policy.getBindings().remove(binding);
      }
      return;
    }

    System.out.println("Role not found in policy; member not removed");
    return;
  }
}

Python

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

def modify_policy_remove_member(policy, role, member):
    """Removes a  member from a role binding."""
    binding = next(b for b in policy["bindings"] if b["role"] == role)
    if "members" in binding and member in binding["members"]:
        binding["members"].remove(member)
    print(binding)
    return policy

Set the allow policy

After you modify the allow policy to grant and revoke the desired roles, call setIamPolicy() to make the updates.

gcloud CLI

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

gcloud RESOURCE_TYPE set-iam-policy RESOURCE_ID PATH

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, or organizations.
  • RESOURCE_ID: Your Google Cloud project, folder, or organization ID. Project IDs are alphanumeric, like my-project. Folder and organization IDs are numeric, like 123456789012.
  • 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 in policy.json as the allow policy for the project my-project:

gcloud projects set-iam-policy my-project ~/policy.json

REST

The Resource Manager API's setIamPolicy 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. For projects and organizations, use v1. For folders, use v2.
  • RESOURCE_TYPE: The resource type whose policy you want to manage. Use the value projects, folders, or organizations.
  • RESOURCE_ID: Your Google Cloud project, organization, or folder ID. Project IDs are alphanumeric strings, like my-project. Folder and organization IDs are numeric, like 123456789012.
  • POLICY: A JSON representation of the policy that you want to set. For more information about the format of a policy, see the Policy reference.

    For example, to set the allow policy shown in the previous step, replace POLICY with the following:

    {
      "version": 1,
      "etag": "BwUqLaVeua8=",
      "bindings": [
        {
          "role": "roles/iam.serviceAccountUser",
          "members": [
            "user:robin@example.com"
          ]
        },
        {
          "role": "roles/owner",
          "members": [
            "user:owner@example.com"
          ]
        }
      ]
    }
    

HTTP method and URL:

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

Request JSON body:

{
  "policy": POLICY
}

To send your request, expand one of these options:

The response contains the updated allow policy.

C#


using Google.Apis.Auth.OAuth2;
using Google.Apis.CloudResourceManager.v1;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy SetPolicy(string projectId, Policy policy)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);
        var service = new CloudResourceManagerService(
            new CloudResourceManagerService.Initializer
            {
                HttpClientInitializer = credential
            });

        return service.Projects.SetIamPolicy(new SetIamPolicyRequest
        {
            Policy = policy
        }, projectId).Execute();
    }
}

Java

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.cloudresourcemanager.v3.CloudResourceManager;
import com.google.api.services.cloudresourcemanager.v3.model.Policy;
import com.google.api.services.cloudresourcemanager.v3.model.SetIamPolicyRequest;
import com.google.api.services.iam.v1.IamScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class SetPolicy {

  // Sets a project's policy.
  public static void setPolicy(Policy policy, String projectId) {
    // policy = service.Projects.GetIAmPolicy(new GetIamPolicyRequest(), your-project-id).Execute();
    // projectId = "my-project-id"

    CloudResourceManager service = null;
    try {
      service = createCloudResourceManagerService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e.toString());
      return;
    }

    try {
      SetIamPolicyRequest request = new SetIamPolicyRequest();
      request.setPolicy(policy);
      Policy response = service.projects().setIamPolicy(projectId, request).execute();
      System.out.println("Policy set: " + response.toString());
    } catch (IOException e) {
      System.out.println("Unable to set policy: \n" + e.toString());
    }
  }

  public static CloudResourceManager createCloudResourceManagerService()
      throws IOException, GeneralSecurityException {
    // Use the Application Default Credentials strategy for authentication. For more info, see:
    // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

    CloudResourceManager service =
        new CloudResourceManager.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

def set_policy(project_id, policy):
    """Sets IAM policy for a project."""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )
    service = googleapiclient.discovery.build(
        "cloudresourcemanager", "v1", credentials=credentials
    )

    policy = (
        service.projects()
        .setIamPolicy(resource=project_id, body={"policy": policy})
        .execute()
    )
    print(policy)
    return policy

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