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.

You can manage user roles with the GCP Console, the gcloud command-line tool, the REST API, or the client libraries. Using the GCP 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 Cloud Identity-Aware Proxy (Cloud IAP) to secure access to your applications, see the Cloud IAP documentation.

Before you begin

Using the GCP Console

Using the GCP Console is a quick and easy way to manage user roles. When you grant a user a role, they don't receive an invite email. Their access is updated directly.

Granting access

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

  1. Open the IAM page in the GCP Console.

    Open the IAM page

  2. Click Select a project, choose a project, and click Open.

  3. Click Add.

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

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

  6. Click Save.

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

  1. Open the IAM & Admin Projects page in the GCP Console.

    Open the IAM & Admin Projects page

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

  3. Click the Show Info Panel, followed by the Permissions tab.

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

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

Revoking access

  1. Open the IAM page in the Google Cloud Platform Console.

    Open the IAM page

  2. Click Select a project.

  3. Select a project and click Open.

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

  5. Click the Delete 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 user, run the gcloud tool's add-iam-policy-binding command:

gcloud [GROUP] add-iam-policy-binding [RESOURCE] \
    --member user:[EMAIL] --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.
  • [EMAIL]: The user's email address.
  • [ROLE_ID]: The name of the role.

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

gcloud projects add-iam-policy-binding my-project \
    --member user:alice@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 user:[EMAIL] --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.
  • [EMAIL]: The user's email address.
  • [ROLE_ID]: The name of the role.

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

gcloud projects remove-iam-policy-binding my-project \
    --member user:bob@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 GCP 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 alice@example.com has been granted the Owner role, and bob@example.com and service-account-13@appspot.gserviceaccount.com have been granted the Editor role:

{
  "bindings":[
    {
      "members":[
        "user:alice@example.com"
      ],
      "role":"roles/owner"
    },
    {
      "members":[
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:bob@example.com"
      ],
      "role":"roles/editor"
    }
  ],
  "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 GCP 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 sections below demonstrate how to get, modify, and set a policy for a project.

Getting the current policy

GCLOUD COMMAND

Run the get-iam-policy command:

gcloud projects get-iam-policy [PROJECT_ID] --format [FORMAT] > [FILE-PATH]

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

Call getIamPolicy():

POST https://cloudresourcemanager.googleapis.com/v1/projects/[PROJECT_ID]:getIamPolicy

Replace [PROJECT_ID] with the project you are getting information about (for example, my-project).

The response contains 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 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;
    }
}

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):
    """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={}).execute()
    print(policy)
    return policy

Modifying a policy

Programmatically or using a text editor, modify the policy to grant or revoke roles to given users.

Granting a role

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

GCLOUD COMMAND

The following example grants the Editor role to eve@example.com. To grant this role, append the user to the members array for the binding:

{
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:bob@example.com",
    "user:eve@example.com"
  ],
  "role":"roles/editor"
}

REST API

The following example grants the Editor role to eve@example.com. To grant this role, append the user to the members array for the binding:

{
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:bob@example.com",
    "user:eve@example.com"
  ],
  "role":"roles/editor"
}

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;
    }
}

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

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

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

REST API

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

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

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;
    }
}

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

Delete the desired members or bindings from the bindings array for the policy.

REST API

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;
        }
    }
}

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:

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

Call setIamPolicy():

POST https://cloudresourcemanager.googleapis.com/v1/projects/[PROJECT_ID]:setIamPolicy

Replace [PROJECT_ID] with the project you are updating (for example, my-project).

The body of the request must contain the updated IAM policy.

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();
    }
}

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

¿Te sirvió esta página? Envíanos tu opinión:

Enviar comentarios sobre…

Cloud IAM Documentation