Granting, changing, and revoking access to resources

This page describes how to grant, change, and revoke access to a resource. You can grant varying levels of access for resources you own to different users by using fine-grained Cloud IAM roles.

The examples on this page show how to modify access to a project. However, you can adapt these steps to modify access to any Google Cloud resource that supports Cloud IAM policy. For details about how to modify access to a specific resource, see the resource's reference documentation.

You can manage user roles with the Cloud Console, the gcloud command-line tool, the REST API, or the client libraries. Using the Cloud Console is the easiest method and is covered in the first half of this article, as is making quick updates using the gcloud command-line tool. Using programmatic methods for more complex scenarios is covered in the second half.

If you want to use Cloud IAM with Identity-Aware Proxy (IAP) to secure access to your applications, see the IAP documentation.

Before you begin

Using the Cloud Console

Using the Cloud Console is a quick and easy way to manage user roles.

Granting access

To add a team member to a project and grant them a Cloud IAM role:

  1. In the Cloud Console, go to the IAM page.

    Go to the IAM page

  2. Click Add.

  3. Enter an email address. You can add individuals, service accounts, or Google Groups as members, but every project must have at least one individual as a member.

  4. Select a role. Roles give members the appropriate level of permission. For best security practices, we strongly recommend giving the member the least amount of privilege needed. Members with Owner-level permissions are also project owners and can manage all aspects of the project, including shutting it down.

  5. Click Save.

To grant a role to a member for more than one project:

  1. In the Cloud Console, go to the Manage resources page.

    Open the Manage resources page

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

  3. Click Show info panel, followed by the Permissions tab.

  4. Enter an email address in the New members field, and select the desired role from the dropdown menu.

  5. Click Save. The member is granted the selected role in each of the selected projects.

Revoking access

  1. In the Cloud Console, go to the IAM page.

    Go to the IAM page

  2. Locate the member for whom you want to revoke access, and then click the Edit button on the right.

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

Modifying access

There is no special procedure for modifying access. Simply follow the steps for granting and revoking access until the user has the desired roles.

Using gcloud for quick updates

You can also quickly grant or revoke access using the gcloud command-line tool.

Granting access

To quickly grant a role to a member, run the gcloud tool's add-iam-policy-binding command:

gcloud group add-iam-policy-binding resource \
    --member=member --role=role-id

Provide the following values:

  • group: The gcloud tool group for the resource you want to update. For example, you can use projects or organizations.
  • resource: The name of the resource.
  • member: An identifier for the member, which usually has the following form: member-type:id. For example, user:my-user@example.com. For a full list of the values that member can have, see the Policy Binding reference.

  • role-id: The name of the role.

For example, to grant the Viewer 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/viewer

Revoking access

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

gcloud group remove-iam-policy-binding resource \
    --member=member --role=role-id

Provide the following values:

  • group: The gcloud tool group for the resource you want to update. For example, you can use projects or organizations.
  • resource: The name of the resource.
  • member: An identifier for the member, which usually has the following form: member-type:id. For example, user:my-user@example.com. For a full list of the values that member can have, see the Policy Binding reference.

  • role-id: The name of the role.

For example, to revoke the Viewer 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/viewer

Controlling access programmatically

In some use cases, it's easier to manage access control programmatically. You can use the gcloud command-line tool, the REST API, or the client libraries to control access programmatically. Programmatic methods are useful when making large-scale or automatic updates that would be time-consuming to perform in the Cloud Console, or by running gcloud commands for each member.

Overview of Cloud IAM policy

Access to a resource is managed through a Cloud IAM policy. A policy is a collection of bindings that associate a member, such as a user account or service account, with a role. Policies are represented using JSON or YAML.

The following example shows a policy where fatima@example.com has been granted the Owner role, and wei@example.com and service-account-13@appspot.gserviceaccount.com have been granted the Editor role:

{
  "bindings": [
    {
      "role": "roles/owner",
      "members": [
        "user:fatima@example.com"
      ]
    },
    {
      "role": "roles/editor",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:wei@example.com"
      ]
    }
  ],
  "etag": "BwUjMhCsNvY=",
  "version": 1
}

You update a policy for a resource by using the read-modify-write pattern. This means there are no distinct methods for creating, modifying, or revoking user access. Instead, all modifications are made by:

  1. Reading the current policy by calling getIamPolicy().
  2. Editing the returned policy, either by using a text editor or programmatically, to add or remove any desired members and their role grants.
  3. Writing the updated policy by calling setIamPolicy().

It's common to grant permissions for an entire project or organization. However, you can also set policies at a more granular level on a wide range of Google Cloud resources, such as Compute Engine instances or Cloud Storage buckets. For a full list of roles and the lowest resource level you can grant each role at, see Understanding Roles.

The following sections show how to get, modify, and set policies for projects. However, you can adapt these instructions to get, modify, and set the policy of any resource that can have its own Cloud IAM policy. To modify the policy of a resource other than a project, find the get-iam-policy and set-iam-policy gcloud commands or the getIamPolicy() and setIamPolicy() REST API methods for the resource. Then, use those commands or methods in the Getting the current policy and Setting a policy sections of this page.

Getting the current policy

gcloud command

Run the get-iam-policy command for the resource. The following example shows the get-iam-policy command for projects:

gcloud projects get-iam-policy project-id --format=format > filepath

Provide the following values:

  • project-id: The project you are updating (for example, my-project).
  • format: The value json or yaml.
  • filepath: The path to a new output file for the policy.

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

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

REST API

The Resource Manager API's projects.getIamPolicy method gets a project's Cloud IAM policy.

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

HTTP method and URL:

POST https://cloudresourcemanager.googleapis.com/v1/projects/project-id:getIamPolicy

Request JSON body:

{
  "options": {
    "requestedPolicyVersion": policy-version
  }
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

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

C#

Before trying this sample, follow the C# setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM C# API reference documentation.


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

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM Java API reference documentation.

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.cloudresourcemanager.CloudResourceManager;
import com.google.api.services.cloudresourcemanager.model.GetIamPolicyRequest;
import com.google.api.services.cloudresourcemanager.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

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM Python API reference documentation.

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

Modifying a policy

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

Granting a role

To grant roles to your members, modify the role bindings in the policy. To learn what roles you can grant, see Understanding roles.

To grant a role that is already included in the policy:

gcloud command

Grant a role by editing the JSON or YAML policy returned by the get-iam-policy command. Note that this policy change will not take effect until you set the updated policy.

The following example grants the Security Reviewer role (roles/iam.securityReviewer) to wei@example.com. To grant this role, append the user to the members array for the binding:

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

REST API

Grant a role by editing the JSON or YAML policy returned by the get-iam-policy command. Note that this policy change will not take effect until you set the updated policy.

The following example grants the Security Reviewer role (roles/iam.securityReviewer) to wei@example.com. To grant this role, append the user to the members array for the binding:

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

C#

Before trying this sample, follow the C# setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM C# API reference documentation.


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

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM Java API reference documentation.

import com.google.api.services.cloudresourcemanager.model.Binding;
import com.google.api.services.cloudresourcemanager.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

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM Python API reference documentation.

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 policy, add a new binding.

gcloud command

Add a new binding by editing the JSON or YAML policy returned by the get-iam-policy command. Note that this policy change will not take effect until you set the updated policy.

The following example grants the Reader role to fatima@example.com. To grant this role, add a new binding to the bindings array for the policy:

{
  "role": "roles/reader",
  "members": [
    "user:fatima@example.com"
  ]
}

REST API

Add a new binding by editing the JSON or YAML policy returned by the get-iam-policy command. Note that this policy change will not take effect until you set the updated policy.

The following example grants the Reader role to fatima@example.com. To grant this role, add a new binding to the bindings array for the policy:

{
  "role": "roles/reader",
  "members": [
    "user:fatima@example.com"
  ]
}

C#

Before trying this sample, follow the C# setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM C# API reference documentation.


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

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM Java API reference documentation.

import com.google.api.services.cloudresourcemanager.model.Binding;
import com.google.api.services.cloudresourcemanager.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

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM Python API reference documentation.

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 role. See the projects.setIamPolicy()reference documentation for more information.

Revoking a role

To revoke a role:

gcloud command

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

To revoke a role from a member, delete the desired members or bindings from the bindings array for the policy.

REST API

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

To revoke a role from a member, delete the desired members or bindings from the bindings array for the policy.

C#

Before trying this sample, follow the C# setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM C# API reference documentation.


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

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM Java API reference documentation.

import com.google.api.services.cloudresourcemanager.model.Binding;
import com.google.api.services.cloudresourcemanager.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

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM Python API reference documentation.

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

Setting a policy

Once you have modified the policy to grant the desired roles, call setIamPolicy() to make the updates.

gcloud command

Use the set-iam-policy command, and provide a path to the JSON file that contains the updated policy. The following example shows the set-iam-policy command for projects:

gcloud projects set-iam-policy project-id filepath

Provide the following values:

  • project-id: The project you are updating (for example, my-project).
  • filepath: The path to a file that contains the new policy.

The response contains the updated policy.

REST API

The Resource Manager API's projects.setIamPolicy method sets the policy in the request as the project's new Cloud IAM policy.

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

  • project-id: Your Google Cloud project ID.
  • 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.

HTTP method and URL:

POST https://cloudresourcemanager.googleapis.com/v1/projects/project-id:setIamPolicy

Request JSON body:

{
  "policy": {
    policy
  }
}

To send your request, expand one of these options:

The response contains the updated 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

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM Java API reference documentation.

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.cloudresourcemanager.CloudResourceManager;
import com.google.api.services.cloudresourcemanager.model.Policy;
import com.google.api.services.cloudresourcemanager.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

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries. For more information, see the Cloud IAM Python API reference documentation.

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

To prevent collisions if multiple sources try to update policy simultaneously, the policy contains an etag value. When you call setIamPolicy(), Cloud IAM compares the etag value in the request with the existing etag, and only writes the policy if the values match.

What's next