Using IAM permissions

Go to concepts

This page describes how to control access to buckets and objects using Identity and Access Management (IAM) permissions. IAM allows you to control who has access to your buckets and objects.

To learn about other ways to control access to buckets and objects, read Overview of Access Control. To learn about controlling access to individual objects in your buckets, see Access Control Lists.

Using IAM with buckets

The following sections show how to complete basic IAM tasks on buckets.

Adding a member to a bucket-level policy

For a list of roles associated with Cloud Storage, see IAM Roles. For information on entities to which you grant IAM roles, see Member Types.

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. Click the Bucket overflow menu () associated with the bucket to which you want to grant a member a role.

  3. Choose Edit bucket permissions.

  4. Click the + Add members button.

  5. In the New members field, enter one or more identities that need access to your bucket.

  6. Select a role (or roles) from the Select a role drop-down menu. The roles you select appear in the pane with a short description of the permissions they grant.

  7. Click Save.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the gsutil iam ch command:

gsutil iam ch [MEMBER_TYPE]:[MEMBER_NAME]:[IAM_ROLE] gs://[BUCKET_NAME]

Where:

  • [MEMBER_TYPE] is the type of member to which you are granting bucket access. For example, user.
  • [MEMBER_NAME] is the name of the member to which you are granting bucket access. For example, jane@gmail.com.
  • [IAM_ROLE] is the IAM role you are granting to the member. For example, roles/storage.objectCreator.
  • [BUCKET_NAME] is the name of the bucket you are granting the member access to. For example, my-bucket.

For more examples of how to format [MEMBER_TYPE]:[MEMBER_NAME]:[IAM_ROLE], see the gsutil iam ch reference page.

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& role, std::string const& member) {
  auto policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));

  if (!policy) throw std::runtime_error(policy.status().message());

  policy->set_version(3);
  for (auto& binding : policy->bindings()) {
    if (binding.role() != role || binding.has_condition()) {
      continue;
    }
    auto& members = binding.members();
    if (std::find(members.begin(), members.end(), member) == members.end()) {
      members.emplace_back(member);
    }
  }

  auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
  if (!updated) throw std::runtime_error(updated.status().message());

  std::cout << "Updated IAM policy bucket " << bucket_name
            << ". The new policy is " << *updated << "\n";
}

C#

For more information, see the Cloud Storage C# API reference documentation.

        private void AddBucketIamMember(string bucketName,
            string role, string member)
        {
            var storage = StorageClient.Create();
            var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions()
            {
                RequestedPolicyVersion = 3
            });
            policy.Version = 3;

            Policy.BindingsData bindingToAdd = new Policy.BindingsData();
            bindingToAdd.Role = role;
            string[] members = { member };
            bindingToAdd.Members = members;
            policy.Bindings.Add(bindingToAdd);

            storage.SetBucketIamPolicy(bucketName, policy);
            Console.WriteLine($"Added {member} with role {role} "
                + $"to {bucketName}");
        }

Go

For more information, see the Cloud Storage Go API reference documentation.

ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
bucket := c.Bucket(bucketName)
policy, err := bucket.IAM().V3().Policy(ctx)
if err != nil {
	return err
}
// Other valid prefixes are "serviceAccount:", "user:"
// See the documentation for more values.
// https://cloud.google.com/storage/docs/access-control/iam
policy.Bindings = append(policy.Bindings, &iampb.Binding{
	Role:    "roles/storage.objectViewer",
	Members: []string{"group:cloud-logs@google.com"},
})
if err := bucket.IAM().V3().SetPolicy(ctx, policy); err != nil {
	return err
}
// NOTE: It may be necessary to retry this operation if IAM policies are
// being modified concurrently. SetPolicy will return an error if the policy
// was modified since it was retrieved.

Java

For more information, see the Cloud Storage Java API reference documentation.

import com.google.cloud.Binding;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AddBucketIamMember {
  /** Example of adding a member to the Bucket-level IAM */
  public static void addBucketIamMember(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // For more information please read:
    // https://cloud.google.com/storage/docs/access-control/iam
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Policy originalPolicy =
        storage.getIamPolicy(bucketName, Storage.BucketSourceOption.requestedPolicyVersion(3));

    String role = "roles/storage.objectViewer";
    String member = "group:example@google.com";

    // getBindingsList() returns an ImmutableList and copying over to an ArrayList so it's mutable.
    List<Binding> bindings = new ArrayList(originalPolicy.getBindingsList());

    // Create a new binding using role and member
    Binding.Builder newMemberBindingBuilder = Binding.newBuilder();
    newMemberBindingBuilder.setRole(role).setMembers(Arrays.asList(member));
    bindings.add(newMemberBindingBuilder.build());

    // Update policy to add member
    Policy.Builder updatedPolicyBuilder = originalPolicy.toBuilder();
    updatedPolicyBuilder.setBindings(bindings).setVersion(3);
    Policy updatedPolicy = storage.setIamPolicy(bucketName, updatedPolicyBuilder.build());

    System.out.printf("Added %s with role %s to %s\n", member, role, bucketName);
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const roleName = 'Role to grant, e.g. roles/storage.objectViewer';
// const members = [
//   'user:jdoe@example.com',    // Example members to grant
//   'group:admins@example.com', // the new role to
// ];

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function addBucketIamMember() {
  // Get a reference to a Google Cloud Storage bucket
  const bucket = storage.bucket(bucketName);

  // Gets and updates the bucket's IAM policy
  const [policy] = await bucket.iam.getPolicy({requestedPolicyVersion: 3});

  // Adds the new roles to the bucket's IAM policy
  policy.bindings.push({
    role: roleName,
    members: members,
  });

  // Updates the bucket's IAM policy
  await bucket.iam.setPolicy(policy);

  console.log(
    `Added the following member(s) with role ${roleName} to ${bucketName}:`
  );

  members.forEach(member => {
    console.log(`  ${member}`);
  });
}

addBucketIamMember().catch(console.error);

PHP

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * Adds a new member / role IAM pair to a given Cloud Storage bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $role the role you want to add a given member to.
 * @param string[] $members the member(s) you want to give the new role for the Cloud
 * Storage bucket.
 *
 * @return void
 */
function add_bucket_iam_member($bucketName, $role, $members)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $policy = $bucket->iam()->policy(['requestedPolicyVersion' => 3]);
    $policy['version'] = 3;

    $policy['bindings'][] = [
        'role' => $role,
        'members' => $members
    ];

    $bucket->iam()->setPolicy($policy);

    printf('Added the following member(s) to role %s for bucket %s' . PHP_EOL, $role, $bucketName);
    foreach ($members as $member) {
        printf('    %s' . PHP_EOL, $member);
    }
}

Python

For more information, see the Cloud Storage Python API reference documentation.

from google.cloud import storage


def add_bucket_iam_member(bucket_name, role, member):
    """Add a new member to an IAM Policy"""
    # bucket_name = "your-bucket-name"
    # role = "IAM role, e.g. roles/storage.objectViewer"
    # member = "IAM identity, e.g. user: name@example.com"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)

    policy.bindings.append({"role": role, "members": {member}})

    bucket.set_iam_policy(policy)

    print("Added {} with role {} to {}.".format(member, role, bucket_name))

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "Your Google Cloud Storage bucket name"
# role        = "Bucket-level IAM role"
# member      = "Bucket-level IAM member"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket = storage.bucket bucket_name

bucket.policy requested_policy_version: 3 do |policy|
  policy.bindings.insert role: role, members: [member]
end

puts "Added #{member} with role #{role} to #{bucket_name}"

JSON

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the following information:

    {
      "bindings":[
        {
          "role": "[IAM_ROLE]",
          "members":[
            "[MEMBER_NAME]"
          ]
        }
      ]
    }

    Where:

    • [IAM_ROLE] is the IAM role you are granting the member. For example, roles/storage.objectCreator.
    • [MEMBER_NAME] is the name of the member to which you are granting bucket access. For example, jane@gmail.com.

      For more examples of how to format [MEMBER_NAME], see the members section here.

  3. Use cURL to call the JSON API with a PUT setIamPolicy request:

    curl -X PUT --data-binary @[JSON_FILE_NAME].json \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/iam"

    Where:

    • [JSON_FILE_NAME] is the name of the file you created in Step 2.
    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the bucket to which you want to give the member access. For example, my-bucket.

Viewing the IAM policy for a bucket

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. Click the Bucket overflow menu () associated with the bucket to which you want to view role members.

  3. Choose Edit bucket permissions.

  4. Expand the desired role to view the members who have been assigned to it.

  5. (Optional) Use the search bar to filter your results by role or member.

    If you search by member, your results display each role that the member is assigned to.

gsutil

Use the gsutil iam get command:

gsutil iam get gs://[BUCKET_NAME]

Where [BUCKET_NAME] is the name of the bucket whose IAM policy you want to view. For example, my-bucket.

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));

  if (!policy) throw std::runtime_error(policy.status().message());
  std::cout << "The IAM policy for bucket " << bucket_name << " is "
            << *policy << "\n";
}

C#

For more information, see the Cloud Storage C# API reference documentation.

        private void ViewBucketIamMembers(string bucketName)
        {
            var storage = StorageClient.Create();
            var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions()
            {
                RequestedPolicyVersion = 3
            });

            foreach (var binding in policy.Bindings)
            {
                Console.WriteLine($"  Role: {binding.Role}");
                Console.WriteLine("  Members:");
                foreach (var member in binding.Members)
                {
                    Console.WriteLine($"    {member}");
                }
                if (binding.Condition != null)
                {
                    Console.WriteLine($"Condition Title: {binding.Condition.Title}");
                    Console.WriteLine($"Condition Description: {binding.Condition.Description}");
                    Console.WriteLine($"Condition Expression: {binding.Condition.Expression}");
                }
            }
        }

Go

For more information, see the Cloud Storage Go API reference documentation.

ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
policy, err := c.Bucket(bucketName).IAM().V3().Policy(ctx)
if err != nil {
	return nil, err
}
for _, binding := range policy.Bindings {
	log.Printf("%q: %q (condition: %v)", binding.Role, binding.Members, binding.Condition)
}

Java

For more information, see the Cloud Storage Java API reference documentation.

import com.google.cloud.Binding;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListBucketIamMembers {
  public static void listBucketIamMembers(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // For more information please read:
    // https://cloud.google.com/storage/docs/access-control/iam
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Policy policy =
        storage.getIamPolicy(bucketName, Storage.BucketSourceOption.requestedPolicyVersion(3));

    // Print binding information
    for (Binding binding : policy.getBindingsList()) {
      System.out.printf("Role: %s Members: %s\n", binding.getRole(), binding.getMembers());

      // Print condition if one is set
      boolean bindingIsConditional = binding.getCondition() != null;
      if (bindingIsConditional) {
        System.out.printf("Condition Title: %s\n", binding.getCondition().getTitle());
        System.out.printf("Condition Description: %s\n", binding.getCondition().getDescription());
        System.out.printf("Condition Expression: %s\n", binding.getCondition().getExpression());
      }
    }
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function viewBucketIamMembers() {
  // Gets and displays the bucket's IAM policy
  // Gets and displays the bucket's IAM policy
  const results = await storage
    .bucket(bucketName)
    .iam.getPolicy({requestedPolicyVersion: 3});

  const bindings = results[0].bindings;

  // Displays the roles in the bucket's IAM policy
  console.log(`Bindings for bucket ${bucketName}:`);
  for (const binding of bindings) {
    console.log(`  Role: ${binding.role}`);
    console.log('  Members:');

    const members = binding.members;
    for (const member of members) {
      console.log(`    ${member}`);
    }

    const condition = binding.condition;
    if (condition) {
      console.log('  Condiiton:');
      console.log(`    Title: ${condition.title}`);
      console.log(`    Description: ${condition.description}`);
      console.log(`    Expression: ${condition.expression}`);
    }
  }
}

viewBucketIamMembers().catch(console.error);

PHP

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * View Bucket IAM members for a given Cloud Storage bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *
 * @return void
 */
function view_bucket_iam_members($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $policy = $bucket->iam()->policy(['requestedPolicyVersion' => 3]);

    printf('Printing Bucket IAM members for Bucket: %s' . PHP_EOL, $bucketName);
    printf(PHP_EOL);

    foreach ($policy['bindings'] as $binding) {
        printf('Role: %s' . PHP_EOL, $binding['role']);
        printf('Members:' . PHP_EOL);
        foreach ($binding['members'] as $member) {
            printf('  %s' . PHP_EOL, $member);
        }

        if (isset($binding['condition'])) {
            $condition = $binding['condition'];
            printf('  with condition:' . PHP_EOL);
            printf('    Title: %s' . PHP_EOL, $condition['title']);
            printf('    Description: %s' . PHP_EOL, $condition['description']);
            printf('    Expression: %s' . PHP_EOL, $condition['expression']);
        }
        printf(PHP_EOL);
    }
}

Python

For more information, see the Cloud Storage Python API reference documentation.

from google.cloud import storage


def view_bucket_iam_members(bucket_name):
    """View IAM Policy for a bucket"""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)

    for binding in policy.bindings:
        print("Role: {}, Members: {}".format(binding["role"], binding["members"]))

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "Your Google Cloud Storage bucket name"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket = storage.bucket bucket_name

policy = bucket.policy requested_policy_version: 3
policy.bindings.each do |binding|
  puts "Role: #{binding.role}"
  puts "Members: #{binding.members}"

  # if a conditional binding exists print the condition.
  if binding.condition
    puts "Condition Title: #{binding.condition.title}"
    puts "Condition Description: #{binding.condition.description}"
    puts "Condition Expression: #{binding.condition.expression}"
  end
end

JSON

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API with a GET getIamPolicy request:

    curl -X GET \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/iam"

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the bucket whose IAM policy you want to view. For example, my-bucket.

Removing a member from a bucket-level policy

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. Click the Bucket overflow menu () associated with the bucket from which you want to remove a member's role.

  3. Choose Edit bucket permissions.

  4. Expand the role that contains the member you are removing.

  5. Click on the trash icon.

  6. In the overlay window that appears, click Remove.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the gsutil iam ch command with a -d flag:

gsutil iam ch -d [MEMBER_TYPE]:[MEMBER_NAME] gs://[BUCKET_NAME]

Where:

  • [MEMBER_TYPE] is the type of the member you are removing from the policy. For example, user.
  • [MEMBER_NAME] is the name of the member you are removing from the policy. For example, jane@gmail.com.
  • [BUCKET_NAME] is the name of the bucket from which you are removing member access. For example, my-bucket.

For more examples of how to format [MEMBER_TYPE]:[MEMBER_NAME], see the gsutil iam ch reference page.

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& role, std::string const& member) {
  auto policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));
  if (!policy) throw std::runtime_error(policy.status().message());

  policy->set_version(3);
  std::vector<google::cloud::storage::NativeIamBinding> updated_bindings;
  for (auto& binding : policy->bindings()) {
    auto& members = binding.members();
    if (binding.role() == role && !binding.has_condition()) {
      members.erase(std::remove(members.begin(), members.end(), member),
                    members.end());
    }
    if (!members.empty()) {
      updated_bindings.emplace_back(std::move(binding));
    }
  }
  policy->bindings() = std::move(updated_bindings);

  auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
  if (!updated) throw std::runtime_error(updated.status().message());

  std::cout << "Updated IAM policy bucket " << bucket_name
            << ". The new policy is " << *updated << "\n";
}

C#

For more information, see the Cloud Storage C# API reference documentation.

private void RemoveBucketIamMember(string bucketName,
    string role, string member)
{
    var storage = StorageClient.Create();
    var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions()
    {
        RequestedPolicyVersion = 3
    });
    policy.Version = 3;
    policy.Bindings.ToList().ForEach(binding =>
    {
        if (binding.Role == role && binding.Condition == null)
        {
            // Remove the role/member combo from the IAM policy.
            binding.Members = binding.Members
                .Where(memberInList => memberInList != member).ToList();
            // Remove role if it contains no members.
            if (binding.Members.Count == 0)
            {
                policy.Bindings.Remove(binding);
            }
        }
    });
    // Set the modified IAM policy to be the current IAM policy.
    storage.SetBucketIamPolicy(bucketName, policy);
    Console.WriteLine($"Removed {member} with role {role} "
        + $"to {bucketName}");
}

Go

For more information, see the Cloud Storage Go API reference documentation.

ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
bucket := c.Bucket(bucketName)
policy, err := bucket.IAM().V3().Policy(ctx)
if err != nil {
	return err
}
// Other valid prefixes are "serviceAccount:", "user:"
// See the documentation for more values.
// https://cloud.google.com/storage/docs/access-control/iam
for _, binding := range policy.Bindings {
	// Only remove unconditional bindings matching role
	if binding.Role == "roles/storage.objectViewer" && binding.Condition == nil {
		// Filter out member.
		i := -1
		for j, member := range binding.Members {
			if member == "group:cloud-logs@google.com" {
				i = j
			}
		}

		if i == -1 {
			return errors.New("No matching binding group found.")
		} else {
			binding.Members = append(binding.Members[:i], binding.Members[i+1:]...)
		}
	}
}
if err := bucket.IAM().V3().SetPolicy(ctx, policy); err != nil {
	return err
}
// NOTE: It may be necessary to retry this operation if IAM policies are
// being modified concurrently. SetPolicy will return an error if the policy
// was modified since it was retrieved.

Java

For more information, see the Cloud Storage Java API reference documentation.

import com.google.cloud.Binding;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.ArrayList;
import java.util.List;

public class RemoveBucketIamMember {
  public static void removeBucketIamMember(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // For more information please read:
    // https://cloud.google.com/storage/docs/access-control/iam
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Policy originalPolicy =
        storage.getIamPolicy(bucketName, Storage.BucketSourceOption.requestedPolicyVersion(3));

    String role = "roles/storage.objectViewer";
    String member = "group:example@google.com";

    // getBindingsList() returns an ImmutableList and copying over to an ArrayList so it's mutable.
    List<Binding> bindings = new ArrayList(originalPolicy.getBindingsList());

    // Remove role-member binding without a condition.
    for (int index = 0; index < bindings.size(); index++) {
      Binding binding = bindings.get(index);
      boolean foundRole = binding.getRole().equals(role);
      boolean foundMember = binding.getMembers().contains(member);
      boolean bindingIsNotConditional = binding.getCondition() == null;

      if (foundRole && foundMember && bindingIsNotConditional) {
        bindings.set(index, binding.toBuilder().removeMembers(member).build());
        break;
      }
    }

    // Update policy to remove member
    Policy.Builder updatedPolicyBuilder = originalPolicy.toBuilder();
    updatedPolicyBuilder.setBindings(bindings).setVersion(3);
    Policy updatedPolicy = storage.setIamPolicy(bucketName, updatedPolicyBuilder.build());

    System.out.printf("Removed %s with role %s from %s\n", member, role, bucketName);
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const roleName = 'Role to grant, e.g. roles/storage.objectViewer';
// const members = [
//   'user:jdoe@example.com',    // Example members to grant
//   'group:admins@example.com', // the new role to
// ];

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function removeBucketIamMember() {
  // Get a reference to a Google Cloud Storage bucket
  const bucket = storage.bucket(bucketName);

  // Gets and updates the bucket's IAM policy
  const [policy] = await bucket.iam.getPolicy({requestedPolicyVersion: 3});

  // Finds and updates the appropriate role-member group, without a condition.
  const index = policy.bindings.findIndex(
    binding => binding.role === roleName && !binding.condition
  );

  const role = policy.bindings[index];
  if (role) {
    role.members = role.members.filter(
      member => members.indexOf(member) === -1
    );

    // Updates the policy object with the new (or empty) role-member group
    if (role.members.length === 0) {
      policy.bindings.splice(index, 1);
    } else {
      policy.bindings.index = role;
    }

    // Updates the bucket's IAM policy
    await bucket.iam.setPolicy(policy);
  } else {
    // No matching role-member group(s) were found
    throw new Error('No matching role-member group(s) found.');
  }

  console.log(
    `Removed the following member(s) with role ${roleName} from ${bucketName}:`
  );
  members.forEach(member => {
    console.log(`  ${member}`);
  });
}

removeBucketIamMember().catch(console.error);

PHP

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * Removes a member / role IAM pair from a given Cloud Storage bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $role the role you want to remove a given member from.
 * @param string $member the member you want to remove from the given role.
 *
 * @return void
 */
function remove_bucket_iam_member($bucketName, $role, $member)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $iam = $bucket->iam();
    $policy = $iam->policy(['requestedPolicyVersion' => 3]);
    $policy['version'] = 3;

    foreach ($policy['bindings'] as $i => $binding) {
        // This example only removes member from bindings without a condition.
        if ($binding['role'] == $role && !isset($binding['condition'])) {
            $key = array_search($member, $binding['members']);
            if ($key !== false) {
                unset($binding['members'][$key]);

                // If the last member is removed from the binding, clean up the
                // binding.
                if (count($binding['members']) == 0) {
                    unset($policy['bindings'][$i]);
                    // Ensure array keys are sequential, otherwise JSON encodes
                    // the array as an object, which fails when calling the API.
                    $policy['bindings'] = array_values($policy['bindings']);
                } else {
                    // Ensure array keys are sequential, otherwise JSON encodes
                    // the array as an object, which fails when calling the API.
                    $binding['members'] = array_values($binding['members']);
                    $policy['bindings'][$i] = $binding;
                }

                $iam->setPolicy($policy);
                printf('User %s removed from role %s for bucket %s' . PHP_EOL, $member, $role, $bucketName);
                return;
            }
        }
    }

    throw new \RuntimeException('No matching role-member group(s) found.');
}

Python

For more information, see the Cloud Storage Python API reference documentation.

from google.cloud import storage


def remove_bucket_iam_member(bucket_name, role, member):
    """Remove member from bucket IAM Policy"""
    # bucket_name = "your-bucket-name"
    # role = "IAM role, e.g. roles/storage.objectViewer"
    # member = "IAM identity, e.g. user: name@example.com"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)

    for binding in policy.bindings:
        print(binding)
        if binding["role"] == role and binding.get("condition") is None:
            binding["members"].discard(member)

    bucket.set_iam_policy(policy)

    print("Removed {} with role {} from {}.".format(member, role, bucket_name))

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "Your Google Cloud Storage bucket name"
# role        = "Bucket-level IAM role"
# member      = "Bucket-level IAM member"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket = storage.bucket bucket_name

bucket.policy requested_policy_version: 3 do |policy|
  policy.bindings.each do |binding|
    if binding.role == role && binding.condition.nil?
      binding.members.delete member
    end
  end
end

puts "Removed #{member} with role #{role} from #{bucket_name}"

JSON

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Get the existing policy applied to your project. To do so, use cURL to call the JSON API with a GET getIamPolicy request:

    curl -X GET \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/iam"

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the bucket whose IAM policy you want to view. For example, my-bucket.
  3. Create a .json file that contains the policy you retrieved in the previous step.

  4. Edit the .json file to remove the member from the policy.

  5. Use cURL to call the JSON API with a PUT setIamPolicy request:

    curl -X PUT --data-binary @[JSON_FILE_NAME].json \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/iam"

    Where:

    • [JSON_FILE_NAME] is the name of the file you created in Step 3.
    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the bucket from which you want to remove member access. For example, my-bucket.

Using IAM Conditions on buckets

The following sections show you how to add and remove IAM Conditions on your buckets. To view the IAM Conditions for your bucket, see Viewing the IAM policy for a bucket. For more information about using IAM Conditions with Cloud Storage, see Conditions.

You must enable uniform bucket-level access on the bucket before adding conditions.

Setting a new condition on a bucket

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. Click the Bucket overflow menu () on the far right of the row associated with the bucket.

  3. Choose Edit bucket permissions.

  4. Click Add members.

  5. For New members, fill out the members to which you want to grant access to your bucket.

  6. For each role to which you want to apply a condition:

    1. Select a Role to grant the members.

    2. Click Add condition to open the Edit condition form.

    3. Fill out the Title of the condition. The Description field is optional.

    4. Use the Condition Builder to build your condition visually, or use the Condition Editor tab to enter the CEL expression.

    5. Click Save to return to the Add members form. To add multiple roles, click Add another role.

  7. Click Save.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

  1. Use the gsutil iam command to save the bucket's IAM policy to a temporary JSON file.

    gsutil iam get gs://[BUCKET_NAME] > /tmp/policy.json

    Where [BUCKET_NAME] is the name of the bucket whose IAM policy you want to retrieve. For example, my-bucket.

  2. Edit the /tmp/policy.json file in a text editor to add new conditions to the bindings in the IAM policy:

    {
      "version": [VERSION],
      "bindings": [
        {
          "role": "[IAM_ROLE]",
          "members": [
            "[MEMBER_NAME]"
          ],
          "condition": {
            "title": "[TITLE]",
            "description": "[DESCRIPTION]",
            "expression": "[EXPRESSION]"
          }
      ],
      "etag": "[ETAG]"
    }

    Where:

    • [VERSION] is the IAM policy version, which is required to be 3 for buckets with IAM Conditions.
    • [IAM ROLE] is the role to which the condition applies. For example, roles/storage.objectCreator.
    • [MEMBER_NAME] is the member to which the condition applies. For example, jane@gmail.com.
    • [TITLE] is the title of the condition. For example, expires in 2019.
    • [DESCRIPTION] is an optional description of the condition. For example, Permission revoked on New Year's.
    • [EXPRESSION] is an attribute-based logic expression. For example, request.time < timestamp(\"2019-01-01T00:00:00Z\"). For more examples of expressions, see the Conditions attribute reference. Note that Cloud Storage only supports the date/time, resource type, and resource name attributes.

    Do not modify [ETAG].

  3. Use gsutil iam to set the modified IAM policy on the bucket.

    gsutil iam set /tmp/policy.json gs://[BUCKET_NAME]

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& role, std::string const& member,
   std::string const& condition_title,
   std::string const& condition_description,
   std::string const& condition_expression) {
  auto policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));
  if (!policy) throw std::runtime_error(policy.status().message());

  policy->set_version(3);
  policy->bindings().emplace_back(gcs::NativeIamBinding(
      role, {member},
      gcs::NativeExpression(condition_expression, condition_title,
                            condition_description)));

  auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
  if (!updated) throw std::runtime_error(updated.status().message());

  std::cout << "Updated IAM policy bucket " << bucket_name
            << ". The new policy is " << *updated << "\n";

  std::cout << "Added member " << member << " with role " << role << " to "
            << bucket_name << ":\n";
  std::cout << "with condition:\n"
            << "\t Title: " << condition_title << "\n"
            << "\t Description: " << condition_description << "\n"
            << "\t Expression: " << condition_expression << "\n";
}

C#

For more information, see the Cloud Storage C# API reference documentation.

        private void AddBucketConditionalIamBinding(string bucketName,
            string role, string member, string title, string description, string expression)
        {
            var storage = StorageClient.Create();
            var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions()
            {
                RequestedPolicyVersion = 3
            });
            policy.Version = 3;

            Policy.BindingsData bindingToAdd = new Policy.BindingsData();
            bindingToAdd.Role = role;
            string[] members = { member };
            bindingToAdd.Members = members;
            bindingToAdd.Condition = new Expr()
            {
                Title = title,
                Description = description,
                Expression = expression
            };
            policy.Bindings.Add(bindingToAdd);

            storage.SetBucketIamPolicy(bucketName, policy);
            Console.WriteLine($"Added {member} with role {role} "
                + $"to {bucketName}");
        }

Go

For more information, see the Cloud Storage Go API reference documentation.

ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
bucket := c.Bucket(bucketName)
policy, err := bucket.IAM().V3().Policy(ctx)
if err != nil {
	return err
}

policy.Bindings = append(policy.Bindings, &iampb.Binding{
	Role:    role,
	Members: []string{member},
	Condition: &expr.Expr{
		Title:       title,
		Description: description,
		Expression:  expression,
	},
})

if err := bucket.IAM().V3().SetPolicy(ctx, policy); err != nil {
	return err
}
// NOTE: It may be necessary to retry this operation if IAM policies are
// being modified concurrently. SetPolicy will return an error if the policy
// was modified since it was retrieved.

Java

For more information, see the Cloud Storage Java API reference documentation.

import com.google.cloud.Binding;
import com.google.cloud.Condition;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AddBucketIamConditionalBinding {
  /** Example of adding a conditional binding to the Bucket-level IAM */
  public static void addBucketIamConditionalBinding(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // For more information please read:
    // https://cloud.google.com/storage/docs/access-control/iam
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Policy originalPolicy =
        storage.getIamPolicy(bucketName, Storage.BucketSourceOption.requestedPolicyVersion(3));

    String role = "roles/storage.objectViewer";
    String member = "group:example@google.com";

    // getBindingsList() returns an ImmutableList and copying over to an ArrayList so it's mutable.
    List<Binding> bindings = new ArrayList(originalPolicy.getBindingsList());

    // Create a condition
    String conditionTitle = "Title";
    String conditionDescription = "Description";
    String conditionExpression =
        "resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")";
    Condition.Builder conditionBuilder = Condition.newBuilder();
    conditionBuilder.setTitle(conditionTitle);
    conditionBuilder.setDescription(conditionDescription);
    conditionBuilder.setExpression(conditionExpression);

    // Add condition to a binding
    Binding.Builder newBindingBuilder =
        Binding.newBuilder()
            .setRole(role)
            .setMembers(Arrays.asList(member))
            .setCondition(conditionBuilder.build());
    bindings.add(newBindingBuilder.build());

    // Update policy with new conditional binding
    Policy.Builder updatedPolicyBuilder = originalPolicy.toBuilder();
    updatedPolicyBuilder.setBindings(bindings).setVersion(3);
    Policy updatedPolicy = storage.setIamPolicy(bucketName, updatedPolicyBuilder.build());

    System.out.printf(
        "Added %s with role %s to %s with condition %s %s %s\n",
        member, role, bucketName, conditionTitle, conditionDescription, conditionExpression);
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const roleName = 'Role to grant, e.g. roles/storage.objectViewer';
// const members = [
//   'user:jdoe@example.com',    // Example members to grant
//   'group:admins@example.com', // the new role to
// ];
// const title = 'Condition title.';
// const description = 'Conditon description.';
// const expression = 'Condition expression.';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function addBucketConditionalBinding() {
  // Get a reference to a Google Cloud Storage bucket
  const bucket = storage.bucket(bucketName);

  // Gets and updates the bucket's IAM policy
  const [policy] = await bucket.iam.getPolicy({requestedPolicyVersion: 3});

  // Set the policy's version to 3 to use condition in bindings.
  policy.version = 3;

  // Adds the new roles to the bucket's IAM policy
  policy.bindings.push({
    role: roleName,
    members: members,
    condition: {
      title: title,
      description: description,
      expression: expression,
    },
  });

  // Updates the bucket's IAM policy
  await bucket.iam.setPolicy(policy);

  console.log(
    `Added the following member(s) with role ${roleName} to ${bucketName}:`
  );

  members.forEach(member => {
    console.log(`  ${member}`);
  });

  console.log('with condition:');
  console.log(`  Title: ${title}`);
  console.log(`  Description: ${description}`);
  console.log(`  Expression: ${expression}`);
}

addBucketConditionalBinding().catch(console.error);

PHP

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * Adds a conditional IAM binding to a bucket's IAM policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $role the role that will be given to members in this binding.
 * @param string[] $members the member(s) that is associated to this binding.
 * @param string $title condition's title
 * @param string $description condition's description
 * @param string $expression the condition specified in CEL expression language.
 *
 * To see how to express a condition in CEL, visit:
 * @see https://cloud.google.com/storage/docs/access-control/iam#conditions.
 *
 * @return void
 */
function add_bucket_conditional_iam_binding($bucketName, $role, $members, $title, $description, $expression)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $policy = $bucket->iam()->policy(['requestedPolicyVersion' => 3]);

    $policy['version'] = 3;

    $policy['bindings'][] = [
        'role' => $role,
        'members' => $members,
        'condition' => [
            'title' => $title,
            'description' => $description,
            'expression' => $expression,
        ],
    ];

    $bucket->iam()->setPolicy($policy);

    printf('Added the following member(s) with role %s to %s:' . PHP_EOL, $role, $bucketName);
    foreach ($members as $member) {
        printf('    %s' . PHP_EOL, $member);
    }
    printf('with condition:' . PHP_EOL);
    printf('    Title: %s' . PHP_EOL, $title);
    printf('    Description: %s' . PHP_EOL, $description);
    printf('    Expression: %s' . PHP_EOL, $expression);
}

Python

For more information, see the Cloud Storage Python API reference documentation.

from google.cloud import storage


def add_bucket_conditional_iam_binding(
    bucket_name, role, title, description, expression, members
):
    """Add a conditional IAM binding to a bucket's IAM policy."""
    # bucket_name = "your-bucket-name"
    # role = "IAM role, e.g. roles/storage.objectViewer"
    # members = {"IAM identity, e.g. user: name@example.com}"
    # title = "Condition title."
    # description = "Condition description."
    # expression = "Condition expression."

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)

    # Set the policy's version to 3 to use condition in bindings.
    policy.version = 3

    policy.bindings.append(
        {
            "role": role,
            "members": members,
            "condition": {
                "title": title,
                "description": description,
                "expression": expression,
            },
        }
    )

    bucket.set_iam_policy(policy)

    print("Added the following member(s) with role {} to {}:".format(role, bucket_name))

    for member in members:
        print("    {}".format(member))

    print("with condition:")
    print("    Title: {}".format(title))
    print("    Description: {}".format(description))
    print("    Expression: {}".format(expression))

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "Your Google Cloud Storage bucket name"
# role        = "Bucket-level IAM role"
# member      = "Bucket-level IAM member"
# title       = "Condition Title"
# description = "Condition Description"
# expression  = "Condition Expression"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket = storage.bucket bucket_name

bucket.policy requested_policy_version: 3 do |policy|
  policy.version = 3
  policy.bindings.insert(
    role:      role,
    members:   member,
    condition: {
      title:       title,
      description: description,
      expression:  expression
    }
  )
end

puts "Added #{member} with role #{role} to #{bucket_name} with condition #{title} #{description} #{expression}"

JSON

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use a GET getIamPolicy request to save the bucket's IAM policy to a temporary JSON file:

    curl \
    'https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/iam' \
    --header 'Authorization: Bearer [OAUTH2_TOKEN]' > /tmp/policy.json

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
  3. Edit the /tmp/policy.json file in a text editor to add new conditions to the bindings in the IAM policy:

    {
          "version": [VERSION],
          "bindings": [
            {
              "role": "[IAM_ROLE]",
              "members": [
                "[MEMBER_NAME]"
              ],
              "condition": {
                "title": "[TITLE]",
                "description": "[DESCRIPTION]",
                "expression": "[EXPRESSION]"
              }
          ],
          "etag": "[ETAG]"
     }

    Where:

    • [VERSION] is the IAM policy version, which is required to be 3 for buckets with IAM Conditions.
    • [IAM_ROLE] is the role to which the condition applies. For example, roles/storage.objectCreator.
    • [MEMBER_NAME] is the member to which the condition applies. For example, jane@gmail.com.
    • [TITLE] is the title of the condition. For example, expires in 2019.
    • [DESCRIPTION] is an optional description of the condition. For example, Permission revoked on New Year's.
    • [EXPRESSION] is an attribute-based logic expression. For example, request.time < timestamp(\"2019-01-01T00:00:00Z\"). For more examples of expressions, see the Conditions attribute reference. Note that Cloud Storage only supports the date/time, resource type, and resource name attributes.

      Do not modify [ETAG].

  4. Use a PUT setIamPolicy request to set the modified IAM policy on the bucket:

    curl -X PUT --data-binary @/tmp/policy.json \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/iam"

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.

Removing a condition from a bucket

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. Click the Bucket overflow menu () on the far right of the row associated with the bucket.

  3. Choose Edit bucket permissions.

  4. Expand the role that contains the condition you are removing.

  5. Click the Edit menu (Edit menu icon.) for the member associated with the condition.

  6. In the Edit permissions overlay that appears, click on the name of the condition you want to delete.

  7. In the Edit condition overlay that appears, click Delete, then Confirm.

  8. Click Save.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

  1. Use the gsutil iam command to save the bucket's IAM policy to a temporary JSON file.

    gsutil iam get gs://[BUCKET_NAME] > /tmp/policy.json
  2. Edit the /tmp/policy.json file in a text editor to remove conditions from the IAM policy.

  3. Use gsutil iam to set the modified IAM policy on the bucket.

    gsutil iam set /tmp/policy.json gs://[BUCKET_NAME]

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& role, std::string const& condition_title,
   std::string const& condition_description,
   std::string const& condition_expression) {
  auto policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));
  if (!policy) throw std::runtime_error(policy.status().message());

  policy->set_version(3);
  auto& bindings = policy->bindings();
  auto e = std::remove_if(
      bindings.begin(), bindings.end(),
      [role, condition_title, condition_description,
       condition_expression](gcs::NativeIamBinding b) {
        return (b.role() == role && b.has_condition() &&
                b.condition().title() == condition_title &&
                b.condition().description() == condition_description &&
                b.condition().expression() == condition_expression);
      });
  if (e == bindings.end()) {
    std::cout << "No matching binding group found.\n";
    return;
  }
  bindings.erase(e);
  auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
  if (!updated) throw std::runtime_error(updated.status().message());

  std::cout << "Conditional binding was removed.\n";
}

C#

For more information, see the Cloud Storage C# API reference documentation.

private void RemoveBucketConditionalIamBinding(string bucketName,
    string role, string title, string description, string expression)
{
    var storage = StorageClient.Create();
    var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions()
    {
        RequestedPolicyVersion = 3
    });
    policy.Version = 3;
    if (policy.Bindings.ToList().RemoveAll(binding => binding.Role == role
        && binding.Condition != null
        && binding.Condition.Title == title
        && binding.Condition.Description == description
        && binding.Condition.Expression == expression) > 0)
    {
        // Set the modified IAM policy to be the current IAM policy.
        storage.SetBucketIamPolicy(bucketName, policy);
        Console.WriteLine("Conditional Binding was removed.");
    }
    else
    {
        Console.WriteLine("No matching conditional binding found.");
    }
}

Go

For more information, see the Cloud Storage Go API reference documentation.

ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
bucket := c.Bucket(bucketName)
policy, err := bucket.IAM().V3().Policy(ctx)
if err != nil {
	return err
}

// Find the index of the binding matching inputs
i := -1
for j, binding := range policy.Bindings {
	if binding.Role == role && binding.Condition != nil {
		condition := binding.Condition
		if condition.Title == title &&
			condition.Description == description &&
			condition.Expression == expression {
			i = j
		}
	}
}

if i == -1 {
	return errors.New("No matching binding group found.")
}

// Get a slice of the bindings, removing the binding at index i
policy.Bindings = append(policy.Bindings[:i], policy.Bindings[i+1:]...)

if err := bucket.IAM().V3().SetPolicy(ctx, policy); err != nil {
	return err
}
// NOTE: It may be necessary to retry this operation if IAM policies are
// being modified concurrently. SetPolicy will return an error if the policy
// was modified since it was retrieved.

Java

For more information, see the Cloud Storage Java API reference documentation.

import com.google.cloud.Binding;
import com.google.cloud.Condition;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class RemoveBucketIamConditionalBinding {
  /** Example of removing a conditional binding to the Bucket-level IAM */
  public static void removeBucketIamConditionalBinding(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // For more information please read:
    // https://cloud.google.com/storage/docs/access-control/iam
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Policy originalPolicy =
        storage.getIamPolicy(bucketName, Storage.BucketSourceOption.requestedPolicyVersion(3));

    String role = "roles/storage.objectViewer";

    // getBindingsList() returns an ImmutableList and copying over to an ArrayList so it's mutable.
    List<Binding> bindings = new ArrayList(originalPolicy.getBindingsList());

    // Create a condition to compare against
    Condition.Builder conditionBuilder = Condition.newBuilder();
    conditionBuilder.setTitle("Title");
    conditionBuilder.setDescription("Description");
    conditionBuilder.setExpression(
        "resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")");

    Iterator iterator = bindings.iterator();
    while (iterator.hasNext()) {
      Binding binding = (Binding) iterator.next();
      boolean foundRole = binding.getRole().equals(role);
      boolean conditionsEqual = conditionBuilder.build().equals(binding.getCondition());

      // Remove condition when the role and condition are equal
      if (foundRole && conditionsEqual) {
        iterator.remove();
        break;
      }
    }

    // Update policy to remove conditional binding
    Policy.Builder updatedPolicyBuilder = originalPolicy.toBuilder();
    updatedPolicyBuilder.setBindings(bindings).setVersion(3);
    Policy updatedPolicy = storage.setIamPolicy(bucketName, updatedPolicyBuilder.build());

    System.out.println("Conditional Binding was removed.");
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const roleName = 'Role to grant, e.g. roles/storage.objectViewer';
// const title = 'Condition title.';
// const description = 'Conditon description.';
// const expression = 'Condition expression.';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function removeBucketConditionalBinding() {
  // Get a reference to a Google Cloud Storage bucket
  const bucket = storage.bucket(bucketName);

  // Gets and updates the bucket's IAM policy
  const [policy] = await bucket.iam.getPolicy({requestedPolicyVersion: 3});

  // Set the policy's version to 3 to use condition in bindings.
  policy.version = 3;

  // Finds and removes the appropriate role-member group with specific condition.
  const index = policy.bindings.findIndex(
    binding =>
      binding.role === roleName &&
      binding.condition &&
      binding.condition.title === title &&
      binding.condition.description === description &&
      binding.condition.expression === expression
  );

  const binding = policy.bindings[index];
  if (binding) {
    policy.bindings.splice(index, 1);

    // Updates the bucket's IAM policy
    await bucket.iam.setPolicy(policy);

    console.log('Conditional Binding was removed.');
  } else {
    // No matching role-member group with specific condition were found
    throw new Error('No matching binding group found.');
  }
}

removeBucketConditionalBinding().catch(console.error);

PHP

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * Removes a conditional IAM binding from a bucket's IAM policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $role the role that will be given to members in this binding.
 * @param string $title condition's title
 * @param string $description condition's description
 * @param string $expression the condition specified in CEL expression language.
 *
 * To see how to express a condition in CEL, visit:
 * @see https://cloud.google.com/storage/docs/access-control/iam#conditions.
 *
 * @return void
 */
function remove_bucket_conditional_iam_binding($bucketName, $role, $title, $description, $expression)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $policy = $bucket->iam()->policy(['requestedPolicyVersion' => 3]);

    $policy['version'] = 3;

    $key_of_conditional_binding = null;
    foreach ($policy['bindings'] as $key => $binding) {
        if ($binding['role'] == $role && isset($binding['condition'])) {
            $condition = $binding['condition'];
            if ($condition['title'] == $title
                 && $condition['description'] == $description
                 && $condition['expression'] == $expression) {
                $key_of_conditional_binding = $key;
                break;
            }
        }
    }

    if ($key_of_conditional_binding != null) {
        unset($policy['bindings'][$key_of_conditional_binding]);
        // Ensure array keys are sequential, otherwise JSON encodes
        // the array as an object, which fails when calling the API.
        $policy['bindings'] = array_values($policy['bindings']);
        $bucket->iam()->setPolicy($policy);
        print('Conditional Binding was removed.' . PHP_EOL);
    } else {
        print('No matching conditional binding found.' . PHP_EOL);
    }
}

Python

For more information, see the Cloud Storage Python API reference documentation.

from google.cloud import storage


def remove_bucket_conditional_iam_binding(
    bucket_name, role, title, description, expression
):
    """Remove a conditional IAM binding from a bucket's IAM policy."""
    # bucket_name = "your-bucket-name"
    # role = "IAM role, e.g. roles/storage.objectViewer"
    # title = "Condition title."
    # description = "Condition description."
    # expression = "Condition expression."

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)

    # Set the policy's version to 3 to use condition in bindings.
    policy.version = 3

    condition = {
        "title": title,
        "description": description,
        "expression": expression,
    }
    policy.bindings = [
        binding
        for binding in policy.bindings
        if not (binding["role"] == role and binding.get("condition") == condition)
    ]

    bucket.set_iam_policy(policy)

    print("Conditional Binding was removed.")

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "Your Google Cloud Storage bucket name"
# role        = "Bucket-level IAM role"
# title       = "Condition Title"
# description = "Condition Description"
# expression  = "Condition Expression"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket = storage.bucket bucket_name

bucket.policy requested_policy_version: 3 do |policy|
  policy.version = 3

  binding_to_remove = nil
  policy.bindings.each do |b|
    condition = {
      title:       title,
      description: description,
      expression:  expression
    }
    if (b.role == role) && (b.condition &&
      b.condition.title == title &&
      b.condition.description == description &&
      b.condition.expression == expression)
      binding_to_remove = b
    end
  end
  if binding_to_remove
    policy.bindings.remove binding_to_remove
    puts "Conditional Binding was removed."
  else
    puts "No matching conditional binding found."
  end
end

JSON

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use a GET getIamPolicy request to save the bucket's IAM policy to a temporary JSON file:

    curl \
    'https://storage.googleapis.com/storage/v1/b/[BUCKET]/iam' \
    --header 'Authorization: Bearer [OAUTH2_TOKEN]' > /tmp/policy.json

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
  3. Edit the /tmp/policy.json file in a text editor to remove conditions from the IAM policy.

  4. Use a PUT setIamPolicy request to set the modified IAM policy on the bucket:

    curl -X PUT --data-binary @/tmp/policy.json \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/iam"

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the bucket whose IAM policy you want to modify. For example, my-bucket.

Using IAM with projects

The following sections show how to complete basic IAM tasks on projects. Note that these tasks use a separate command line command, gcloud, and a separate endpoint, cloudresourcemanager.googleapis.com, compared to most Cloud Storage tasks.

To complete the following tasks, you must have the resourcemanager.projects.getIamPolicy and resourcemanager.projects.setIamPolicy IAM permissions.

Adding a member to a project-level policy

For a list of roles associated with Cloud Storage, see IAM Roles. For information on entities to which you grant IAM roles, see Member Types.

Console

  1. Open the IAM & Admin browser in the Google Cloud Console.
    Open the IAM & Admin browser
  2. In the project drop-down menu on the top bar, select the project to which you want to add a member.

  3. Click Add. The Add members, roles to project dialog appears.

  4. In the New members field, specify the name of the entity to which you are granting access.

  5. In the Select a role drop down, grant the appropriate role to the member.

    Roles that affect Cloud Storage buckets and objects are found in the Project and Storage submenus.

  6. Click Save.

gsutil

Project-level IAM policies are managed through the gcloud command, which is part of the Google Cloud SDK. To add a project-level policy, use gcloud beta projects add-iam-policy-binding.

JSON

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the following information:

    {
      "policy": {
        "version": "0",
        "bindings": {
          "role": "[IAM_ROLE]",
          "members": "[MEMBER_NAME]"
        },
      }
    }

    Where:

    • [IAM_ROLE] is the IAM role you are granting the member. For example, roles/storage.objectCreator.
    • [MEMBER_NAME] is the type and name of the member to which you are granting project access. For example, user:jane@gmail.com.
  3. Use cURL to call the Resource Manager API with a POST setIamPolicy request:

    curl -X POST --data-binary @[JSON_FILE_NAME].json \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Type: application/json" \
      "https://cloudresourcemanager.googleapis.com/v1/projects/[PROJECT_ID]:setIamPolicy"

    Where:

    • [JSON_FILE_NAME] is the name of the file you created in Step 2.
    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [PROJECT_ID] is the ID of the project to which you are granting member access. For example, my-project.

Viewing the IAM policy for a project

Console

  1. Open the IAM & Admin browser in the Google Cloud Console.
    Open the IAM & Admin browser
  2. In the project drop-down menu on the top bar, select the project whose policy you want to view.

  3. There are two ways to view permissions for the project:

    • View by Members: View the Role column associated with individual members to see which roles each member has.
    • View by Roles: Use the drop-down associated with individual roles to see which members have the role.

gsutil

Project-level IAM policies are managed through the gcloud command, which is part of the Google Cloud SDK. To view the IAM policy of a project, use gcloud beta projects get-iam-policy command.

JSON

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the Resource Manager API with a POST getIamPolicy request:

    curl -X POST \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Length: 0" \
      "https://cloudresourcemanager.googleapis.com/v1/projects/[PROJECT_ID]:getIamPolicy"

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [PROJECT_ID] is the ID of the project to which you are granting member access. For example, my-project.

Removing a member from a project-level policy

Console

  1. Open the IAM & Admin browser in the Google Cloud Console.
    Open the IAM & Admin browser
  2. In the project drop-down menu on the top bar, select the project from which you want to remove a member.

  3. Make sure you are viewing permissions by Members, and select the members you want to remove.

  4. Click Remove.

  5. In the overlay window that appears, click Confirm.

gsutil

Project-level IAM policies are managed through the gcloud command, which is part of the Google Cloud SDK. To remove a project-level policy, use gcloud beta projects remove-iam-policy-binding.

JSON

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Get the existing policy applied to your project. To do so, use cURL to call the Resource Manager API with a POST getIamPolicy request:

    curl -X POST \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Length: 0" \
      "https://cloudresourcemanager.googleapis.com/v1/projects/[PROJECT_ID]:getIamPolicy"

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [PROJECT_ID] is the ID of the project to which you want to add member access. For example, my-project.
  3. Create a .json file that contains the policy you retrieved in the previous step.

  4. Edit the .json file to remove the member from the policy.

  5. Use cURL to call the Resource Manager API with a POST setIamPolicy request:

    curl -X POST --data-binary @[JSON_FILE_NAME].json \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Type: application/json" \
      "https://cloudresourcemanager.googleapis.com/v1/projects/[PROJECT_ID]:setIamPolicy"

    Where:

    • [JSON_FILE_NAME] is the name of the file you created in Step 2.
    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [PROJECT_ID] is the ID of the project to which you want to grant member access. For example, my-project.

What's next