Set and manage IAM policies on buckets

Overview

This page describes how to set Identity and Access Management (IAM) policies on buckets, so you can control access to objects and managed folders within those buckets.

If you're looking for other methods of access control, see the following resources:

Required roles

To get the permissions that you need to set and manage IAM policies for a bucket, ask your administrator to grant you the Storage Admin (roles/storage.admin) IAM role for the bucket.

This role contains the following permissions, which are required to set and manage IAM policies for buckets:

  • storage.buckets.get

  • storage.buckets.getIamPolicy

  • storage.buckets.setIamPolicy

  • storage.buckets.update

  • storage.buckets.list

    • This permission is only required if you plan on using the Google Cloud console to perform the tasks on this page.

You can also get these permissions with custom roles.

Add a principal 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 Principal identifiers.

Console

  1. In the Google Cloud console, go to the Cloud Storage Buckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket for which you want to grant a principal a role.

  3. Select the Permissions tab near the top of the page.

  4. Click the Grant access button.

    The Add principals dialog appears.

  5. In the New principals 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.

To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, see Troubleshooting.

Command line

Use the buckets add-iam-policy-binding command:

gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME --member=PRINCIPAL_IDENTIFIER --role=IAM_ROLE

Where:

  • BUCKET_NAME is the name of the bucket you are granting the principal access to. For example, my-bucket.

  • PRINCIPAL_IDENTIFIER identifies who you are granting bucket access to. For example, user:jeffersonloveshiking@gmail.com. For a list of principal identifier formats, see Principal identifiers.

  • IAM_ROLE is the IAM role you are granting to the principal. For example, roles/storage.objectViewer.

Client libraries

C++

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

namespacegcs=::google::cloud::storage;
using::google::cloud::StatusOr;
[](gcs::Clientclient,std::stringconst&bucket_name,
std::stringconst&role,std::stringconst&member){
autopolicy=client.GetNativeBucketIamPolicy(
bucket_name,gcs::RequestedPolicyVersion(3));
if(!policy)throwstd::move(policy).status();
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);
}
}
autoupdated=client.SetNativeBucketIamPolicy(bucket_name,*policy);
if(!updated)throwstd::move(updated).status();
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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.


usingGoogle.Apis.Storage.v1.Data;
usingGoogle.Cloud.Storage.V1 ;
usingSystem;
usingSystem.Collections.Generic;
publicclassAddBucketIamMemberSample
{
publicPolicyAddBucketIamMember(
stringbucketName="your-unique-bucket-name",
stringrole="roles/storage.objectViewer",
stringmember="serviceAccount:dev@iam.gserviceaccount.com")
{
varstorage=StorageClient .Create ();
varpolicy=storage.GetBucketIamPolicy(bucketName,newGetBucketIamPolicyOptions
{
RequestedPolicyVersion=3
});
// Set the policy schema version. For more information, please refer to https://cloud.google.com/iam/docs/policies#versions.
policy.Version=3;
Policy.BindingsDatabindingToAdd=newPolicy.BindingsData
{
Role=role,
Members=newList<string>{member}
};
policy.Bindings.Add(bindingToAdd);
varbucketIamPolicy=storage.SetBucketIamPolicy(bucketName,policy);
Console.WriteLine($"Added {member} with role {role} "+$"to {bucketName}");
returnbucketIamPolicy;
}
}

Go

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

import(
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/iam"
"cloud.google.com/go/storage"
)
// addBucketIAMMember adds the bucket IAM member to permission role.
funcaddBucketIAMMember(wio.Writer ,bucketNamestring)error{
// bucketName := "bucket-name"
ctx:=context.Background()
client,err:=storage.NewClient(ctx)
iferr!=nil{
returnfmt.Errorf("storage.NewClient: %w",err)
}
deferclient.Close()
ctx,cancel:=context.WithTimeout(ctx,time.Second*10)
defercancel()
bucket:=client.Bucket (bucketName)
policy,err:=bucket.IAM ().Policy(ctx)
iferr!=nil{
returnfmt.Errorf("Bucket(%q).IAM().Policy: %w",bucketName,err)
}
// Other valid prefixes are "serviceAccount:", "user:"
// See the documentation for more values.
// https://cloud.google.com/storage/docs/access-control/iam
identity:="group:cloud-logs@google.com"
varroleiam.RoleName ="roles/storage.objectViewer"
policy.Add(identity,role)
iferr:=bucket.IAM ().SetPolicy(ctx,policy);err!=nil{
returnfmt.Errorf("Bucket(%q).IAM().SetPolicy: %w",bucketName,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.
fmt.Fprintf(w,"Added %v with role %v to %v\n",identity,role,bucketName)
returnnil
}

Java

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.


importcom.google.cloud.Binding ;
importcom.google.cloud.Policy ;
importcom.google.cloud.storage.Storage ;
importcom.google.cloud.storage.StorageOptions ;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.List;
publicclass AddBucketIamMember{
/** Example of adding a member to the Bucket-level IAM */
publicstaticvoidaddBucketIamMember(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=newArrayList(originalPolicy.getBindingsList ());
// Create a new binding using role and member
Binding .BuildernewMemberBindingBuilder=Binding .newBuilder();
newMemberBindingBuilder.setRole(role).setMembers(Arrays.asList(member));
bindings.add(newMemberBindingBuilder.build());
// Update policy to add member
Policy .BuilderupdatedPolicyBuilder=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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// The role to grant
// const roleName = 'roles/storage.objectViewer';
// The members to grant the new role to
// const members = [
// 'user:jdoe@example.com',
// 'group:admins@example.com',
// ];
// Imports the Google Cloud client library
const{Storage}=require('@google-cloud/storage');
// Creates a client
conststorage=newStorage();
asyncfunctionaddBucketIamMember(){
// Get a reference to a Google Cloud Storage bucket
constbucket=storage.bucket(bucketName);
// For more information please read:
// https://cloud.google.com/storage/docs/access-control/iam
const[policy]=awaitbucket.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
awaitbucket.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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

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.
 * (e.g. 'my-bucket')
 * @param string $role The role to which the given member should be added.
 * (e.g. 'roles/storage.objectViewer')
 * @param string[] $members The member(s) to be added to the role.
 * (e.g. ['group:example@google.com'])
 */
function add_bucket_iam_member(string $bucketName, string $role, array $members): void
{
 $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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

fromgoogle.cloudimport storage
defadd_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(f"Added {member} with role {role} to {bucket_name}.")

Ruby

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

defadd_bucket_iam_memberbucket_name:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
require"google/cloud/storage"
storage=Google::Cloud::Storage .new
bucket=storage.bucketbucket_name
role="roles/storage.objectViewer"
member="group:example@google.com"
bucket.policy requested_policy_version:3do|policy|
policy.bindings .insert role:role,members:[member]
end
puts"Added #{member} with role #{role} to #{bucket_name}"
end

REST APIs

JSON

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

  2. Create a JSON file that contains the following information:

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

    Where:

    • IAM_ROLE is the IAM role you are granting. For example, roles/storage.objectViewer.

    • PRINCIPAL_IDENTIFIER identifies who you are granting bucket access to. For example, user:jeffersonloveshiking@gmail.com. For a list of principal identifier formats, see Principal identifiers.

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

    curl -X PUT --data-binary @JSON_FILE_NAME \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    Where:

    • JSON_FILE_NAME is the path for the file that you created in Step 2.

    • BUCKET_NAME is the name of the bucket to which you want to give the principal access. For example, my-bucket.

View the IAM policy for a bucket

Console

  1. In the Google Cloud console, go to the Cloud Storage Buckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket whose policy you want to view.

  3. In the Bucket details page, click the Permissions tab.

    The IAM policy that applies to the bucket appears in the Permissions section.

  4. Optional: Use the Filter bar to filter your results.

    If you search by principal, your results display each role that the principal is granted.

Command line

Use the buckets get-iam-policy command:

gcloud storage buckets get-iam-policy gs://BUCKET_NAME

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

Client libraries

C++

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

namespacegcs=::google::cloud::storage;
using::google::cloud::StatusOr;
[](gcs::Clientclient,std::stringconst&bucket_name){
autopolicy=client.GetNativeBucketIamPolicy(
bucket_name,gcs::RequestedPolicyVersion(3));
if(!policy)throwstd::move(policy).status();
std::cout << "The IAM policy for bucket " << bucket_name << " is "
 << *policy << "\n";
}

C#

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.


usingGoogle.Apis.Storage.v1.Data;
usingGoogle.Cloud.Storage.V1 ;
usingSystem;
publicclassViewBucketIamMembersSample
{
publicPolicyViewBucketIamMembers(stringbucketName="your-unique-bucket-name")
{
varstorage=StorageClient .Create ();
varpolicy=storage.GetBucketIamPolicy(bucketName,newGetBucketIamPolicyOptions
{
RequestedPolicyVersion=3
});
foreach(varbindinginpolicy.Bindings)
{
Console.WriteLine($"Role: {binding.Role}");
Console.WriteLine("Members:");
foreach(varmemberinbinding.Members)
{
Console.WriteLine($"{member}");
}
}
returnpolicy;
}
}

Go

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

import(
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/iam"
"cloud.google.com/go/storage"
)
// getBucketPolicy gets the bucket IAM policy.
funcgetBucketPolicy(wio.Writer ,bucketNamestring)(*iam.Policy3 ,error){
// bucketName := "bucket-name"
ctx:=context.Background()
client,err:=storage.NewClient(ctx)
iferr!=nil{
returnnil,fmt.Errorf("storage.NewClient: %w",err)
}
deferclient.Close()
ctx,cancel:=context.WithTimeout(ctx,time.Second*10)
defercancel()
policy,err:=client.Bucket (bucketName).IAM ().V3 ().Policy(ctx)
iferr!=nil{
returnnil,fmt.Errorf("Bucket(%q).IAM().V3().Policy: %w",bucketName,err)
}
for_,binding:=rangepolicy.Bindings{
fmt.Fprintf(w,"%q: %q (condition: %v)\n",binding.Role ,binding.Members ,binding.Condition)
}
returnpolicy,nil
}

Java

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

importcom.google.cloud.Binding ;
importcom.google.cloud.Policy ;
importcom.google.cloud.storage.Storage ;
importcom.google.cloud.storage.StorageOptions ;
publicclass ListBucketIamMembers{
publicstaticvoidlistBucketIamMembers(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
booleanbindingIsConditional=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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// Imports the Google Cloud client library
const{Storage}=require('@google-cloud/storage');
// Creates a client
conststorage=newStorage();
asyncfunctionviewBucketIamMembers(){
// For more information please read:
// https://cloud.google.com/storage/docs/access-control/iam
constresults=awaitstorage
.bucket(bucketName)
.iam .getPolicy ({requestedPolicyVersion:3});
constbindings=results[0].bindings ;
console.log(`Bindings for bucket ${bucketName}:`);
for(constbindingofbindings){
console.log(` Role: ${binding.role}`);
console.log(' Members:');
constmembers=binding.members;
for(constmemberofmembers){
console.log(` ${member}`);
}
constcondition=binding.condition ;
if(condition){
console.log(' Condition:');
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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

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.
 * (e.g. 'my-bucket')
 */
function view_bucket_iam_members(string $bucketName): void
{
 $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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

fromgoogle.cloudimport storage
defview_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(f"Role: {binding['role']}, Members: {binding['members']}")

Ruby

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

defview_bucket_iam_membersbucket_name:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
require"google/cloud/storage"
storage=Google::Cloud::Storage .new
bucket=storage.bucketbucket_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.
ifbinding.condition
puts"Condition Title: #{binding.condition .title }"
puts"Condition Description: #{binding.condition .description}"
puts"Condition Expression: #{binding.condition .expression }"
end
end
end

REST APIs

JSON

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

  2. Use cURL to call the JSON API with a GET getIamPolicy request:

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

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

Remove a principal from a bucket-level policy

Console

  1. In the Google Cloud console, go to the Cloud Storage Buckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket from which you want to remove a principal's role.

  3. In the Bucket details page, click the Permissions tab.

    The IAM policy that applies to the bucket appears in the Permissions section.

  4. In the View by principals tab, select the checkbox for the principal you're removing.

  5. Click the - Remove access button.

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

To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, see Troubleshooting.

Command line

Use the buckets remove-iam-policy-binding command:

gcloud storage buckets remove-iam-policy-binding gs://BUCKET_NAME --member=PRINCIPAL_IDENTIFIER --role=IAM_ROLE

Where:

  • BUCKET_NAME is the name of the bucket you are revoking access to. For example, my-bucket.

  • PRINCIPAL_IDENTIFIER identifies who you are revoking access from. For example, user:jeffersonloveshiking@gmail.com. For a list of principal identifier formats, see Principal identifiers.

  • IAM_ROLE is the IAM role you are revoking. For example, roles/storage.objectViewer.

Client libraries

C++

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

namespacegcs=::google::cloud::storage;
using::google::cloud::StatusOr;
[](gcs::Clientclient,std::stringconst&bucket_name,
std::stringconst&role,std::stringconst&member){
autopolicy=client.GetNativeBucketIamPolicy(
bucket_name,gcs::RequestedPolicyVersion(3));
if(!policy)throwstd::move(policy).status();
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);
autoupdated=client.SetNativeBucketIamPolicy(bucket_name,*policy);
if(!updated)throwstd::move(updated).status();
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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.


usingGoogle.Cloud.Storage.V1 ;
usingSystem;
usingSystem.Linq;
publicclassRemoveBucketIamMemberSample
{
publicvoidRemoveBucketIamMember(
stringbucketName="your-unique-bucket-name",
stringrole="roles/storage.objectViewer",
stringmember="serviceAccount:dev@iam.gserviceaccount.com")
{
varstorage=StorageClient .Create ();
varpolicy=storage.GetBucketIamPolicy(bucketName,newGetBucketIamPolicyOptions
{
RequestedPolicyVersion=3
});
// Set the policy schema version. For more information, please refer to https://cloud.google.com/iam/docs/policies#versions.
policy.Version=3;
foreach(varbindinginpolicy.Bindings.Where(c=>c.Role==role).ToList())
{
// Remove the role/member combo from the IAM policy.
binding.Members=binding.Members.Where(m=>m!=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} from {bucketName}");
}
}

Go

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

import(
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/iam"
"cloud.google.com/go/storage"
)
// removeBucketIAMMember removes the bucket IAM member.
funcremoveBucketIAMMember(wio.Writer ,bucketNamestring)error{
// bucketName := "bucket-name"
ctx:=context.Background()
client,err:=storage.NewClient(ctx)
iferr!=nil{
returnfmt.Errorf("storage.NewClient: %w",err)
}
deferclient.Close()
ctx,cancel:=context.WithTimeout(ctx,time.Second*10)
defercancel()
bucket:=client.Bucket (bucketName)
policy,err:=bucket.IAM ().Policy(ctx)
iferr!=nil{
returnfmt.Errorf("Bucket(%q).IAM().Policy: %w",bucketName,err)
}
// Other valid prefixes are "serviceAccount:", "user:"
// See the documentation for more values.
// https://cloud.google.com/storage/docs/access-control/iam
// member string, role iam.RoleName
identity:="group:cloud-logs@google.com"
varroleiam.RoleName ="roles/storage.objectViewer"
policy.Remove (identity,role)
iferr:=bucket.IAM ().SetPolicy(ctx,policy);err!=nil{
returnfmt.Errorf("Bucket(%q).IAM().SetPolicy: %w",bucketName,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.
fmt.Fprintf(w,"Removed %v with role %v from %v\n",identity,role,bucketName)
returnnil
}

Java

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.


importcom.google.cloud.Binding ;
importcom.google.cloud.Policy ;
importcom.google.cloud.storage.Storage ;
importcom.google.cloud.storage.StorageOptions ;
importjava.util.ArrayList;
importjava.util.List;
publicclass RemoveBucketIamMember{
publicstaticvoidremoveBucketIamMember(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=newArrayList(originalPolicy.getBindingsList ());
// Remove role-member binding without a condition.
for(intindex=0;index < bindings.size();index++){
Binding binding=bindings.get(index);
booleanfoundRole=binding.getRole ().equals(role);
booleanfoundMember=binding.getMembers ().contains(member);
booleanbindingIsNotConditional=binding.getCondition ()==null;
if(foundRole && foundMember && bindingIsNotConditional){
bindings.set(index,binding.toBuilder ().removeMembers (member).build());
break;
}
}
// Update policy to remove member
Policy .BuilderupdatedPolicyBuilder=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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// The role to revoke
// const roleName = 'roles/storage.objectViewer';
// The members to revoke the roles from
// const members = [
// 'user:jdoe@example.com',
// 'group:admins@example.com',
// ];
// Imports the Google Cloud client library
const{Storage}=require('@google-cloud/storage');
// Creates a client
conststorage=newStorage();
asyncfunctionremoveBucketIamMember(){
// Get a reference to a Google Cloud Storage bucket
constbucket=storage.bucket(bucketName);
// For more information please read:
// https://cloud.google.com/storage/docs/access-control/iam
const[policy]=awaitbucket.iam .getPolicy ({requestedPolicyVersion:3});
// Finds and updates the appropriate role-member group, without a condition.
constindex=policy.bindings .findIndex(
binding=>binding.role===roleName && !binding.condition
);
constrole=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
awaitbucket.iam .setPolicy (policy);
}else{
// No matching role-member group(s) were found
thrownewError('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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

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.
 * (e.g. 'my-bucket')
 * @param string $role The role from which the specified member should be removed.
 * (e.g. 'roles/storage.objectViewer')
 * @param string $member The member to be removed from the specified role.
 * (e.g. 'group:example@google.com')
 */
function remove_bucket_iam_member(string $bucketName, string $role, string $member): void
{
 $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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

fromgoogle.cloudimport storage
defremove_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(f"Removed {member} with role {role} from {bucket_name}.")

Ruby

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

defremove_bucket_iam_memberbucket_name:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# For more information please read: https://cloud.google.com/storage/docs/access-control/iam
require"google/cloud/storage"
storage=Google::Cloud::Storage .new
bucket=storage.bucketbucket_name
role="roles/storage.objectViewer"
member="group:example@google.com"
bucket.policy requested_policy_version:3do|policy|
policy.bindings .each do|binding|
ifbinding.role==role && binding.condition .nil?
binding.members .deletemember
end
end
end
puts"Removed #{member} with role #{role} from #{bucket_name}"
end

REST APIs

JSON

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

  2. Get the existing policy applied to your bucket. To do so, use cURL to call the JSON API with a GET getIamPolicy request:

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    Where 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 principal from the policy.

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

    curl -X PUT --data-binary @JSON_FILE_NAME \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    Where:

    • JSON_FILE_NAME is the path for the file that you created in Step 3.

    • BUCKET_NAME is the name of the bucket from which you want to remove access. For example, my-bucket.

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

Set a new condition on a bucket

Console

  1. In the Google Cloud console, go to the Cloud Storage Buckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket that you want to add a new condition for.

  3. In the Bucket details page, click the Permissions tab.

    The IAM policy that applies to the bucket appears in the Permissions section.

  4. Click + Grant access.

  5. For New principals, fill out the principals 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 principals.

    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 principal form. To add multiple roles, click Add another role.

  7. Click Save.

To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, see Troubleshooting.

Command line

  1. Create a JSON or YAML file that defines the condition, including the title of the condition, the attribute-based logic expression for the condition, and, optionally, a description for the condition.

    Note that Cloud Storage only supports the date/time, resource type, and resource name attributes in the expression.

  2. Use the buckets add-iam-policy-binding command with the --condition-from-file flag:

gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME --member=PRINCIPAL_IDENTIFIER --role=IAM_ROLE --condition-from-file=CONDITION_FILE

Where:

  • BUCKET_NAME is the name of the bucket you are granting the principal access to. For example, my-bucket.

  • PRINCIPAL_IDENTIFIER identifies who the condition applies to. For example, user:jeffersonloveshiking@gmail.com. For a list of principal identifier formats, see Principal identifiers.

  • IAM_ROLE is the IAM role you are granting to the principal. For example, roles/storage.objectViewer.

  • CONDITION_FILE is the file you created in the previous step.

Alternatively, you can include the condition directly in the command with the --condition flag instead of the --condition-from-file flag.

Client libraries

C++

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

namespacegcs=::google::cloud::storage;
using::google::cloud::StatusOr;
[](gcs::Clientclient,std::stringconst&bucket_name,
std::stringconst&role,std::stringconst&member,
std::stringconst&condition_title,
std::stringconst&condition_description,
std::stringconst&condition_expression){
autopolicy=client.GetNativeBucketIamPolicy(
bucket_name,gcs::RequestedPolicyVersion(3));
if(!policy)throwstd::move(policy).status();
policy->set_version(3);
policy->bindings().emplace_back(gcs::NativeIamBinding(
role,{member},
gcs::NativeExpression(condition_expression,condition_title,
condition_description)));
autoupdated=client.SetNativeBucketIamPolicy(bucket_name,*policy);
if(!updated)throwstd::move(updated).status();
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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.


usingGoogle.Apis.Storage.v1.Data;
usingGoogle.Cloud.Storage.V1 ;
usingSystem;
usingSystem.Collections.Generic;
publicclassAddBucketConditionalIamBindingSample
{
/// <summary>
/// Adds a conditional Iam policy to a bucket.
/// </summary>
/// <param name="bucketName">The name of the bucket.</param>
/// <param name="role">The role that members may assume.</param>
/// <param name="member">The identifier of the member who may assume the provided role.</param>
/// <param name="title">Title for the expression.</param>
/// <param name="description">Description of the expression.</param>
/// <param name="expression">Describes the conditions that need to be met for the policy to be applied.
/// It's represented as a string using Common Expression Language syntax.</param>
publicPolicyAddBucketConditionalIamBinding(
stringbucketName="your-unique-bucket-name",
stringrole="roles/storage.objectViewer",
stringmember="serviceAccount:dev@iam.gserviceaccount.com",
stringtitle="title",
stringdescription="description",
stringexpression="resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")")
{
varstorage=StorageClient .Create ();
varpolicy=storage.GetBucketIamPolicy(bucketName,newGetBucketIamPolicyOptions
{
RequestedPolicyVersion=3
});
// Set the policy schema version. For more information, please refer to https://cloud.google.com/iam/docs/policies#versions.
policy.Version=3;
Policy.BindingsDatabindingToAdd=newPolicy.BindingsData
{
Role=role,
Members=newList<string>{member},
Condition=newExpr
{
Title=title,
Description=description,
Expression=expression
}
};
policy.Bindings.Add(bindingToAdd);
varbucketIamPolicy=storage.SetBucketIamPolicy(bucketName,policy);
Console.WriteLine($"Added {member} with role {role} "+$"to {bucketName}");
returnbucketIamPolicy;
}
}

Go

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

import(
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/iam/apiv1/iampb"
"cloud.google.com/go/storage"
"google.golang.org/genproto/googleapis/type/expr"
)
// addBucketConditionalIAMBinding adds bucket conditional IAM binding.
funcaddBucketConditionalIAMBinding(wio.Writer ,bucketName,role,member,title,description,expressionstring)error{
// bucketName := "bucket-name"
// role := "bucket-level IAM role"
// member := "bucket-level IAM member"
// title := "condition title"
// description := "condition description"
// expression := "condition expression"
ctx:=context.Background()
client,err:=storage.NewClient(ctx)
iferr!=nil{
returnfmt.Errorf("storage.NewClient: %w",err)
}
deferclient.Close()
ctx,cancel:=context.WithTimeout(ctx,time.Second*10)
defercancel()
bucket:=client.Bucket (bucketName)
policy,err:=bucket.IAM ().V3().Policy (ctx)
iferr!=nil{
returnfmt.Errorf("Bucket(%q).IAM().V3().Policy: %w",bucketName,err)
}
policy.Bindings=append(policy.Bindings,&iampb.Binding {
Role:role,
Members:[]string{member},
Condition:&expr.Expr{
Title:title,
Description:description,
Expression:expression,
},
})
iferr:=bucket.IAM ().V3().SetPolicy(ctx,policy);err!=nil{
returnfmt.Errorf("Bucket(%q).IAM().V3().SetPolicy: %w",bucketName,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.
fmt.Fprintf(w,"Added %v with role %v to %v with condition %v %v %v\n",member,role,bucketName,title,description,expression)
returnnil
}

Java

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.


importcom.google.cloud.Binding ;
importcom.google.cloud.Condition ;
importcom.google.cloud.Policy ;
importcom.google.cloud.storage.Storage ;
importcom.google.cloud.storage.StorageOptions ;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.List;
publicclass AddBucketIamConditionalBinding{
/** Example of adding a conditional binding to the Bucket-level IAM */
publicstaticvoidaddBucketIamConditionalBinding(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";
// Create a condition
String conditionTitle="Title";
String conditionDescription="Description";
String conditionExpression=
"resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")";
Condition .BuilderconditionBuilder=Condition .newBuilder();
conditionBuilder.setTitle(conditionTitle);
conditionBuilder.setDescription(conditionDescription);
conditionBuilder.setExpression(conditionExpression);
// getBindingsList() returns an ImmutableList, we copy over to an ArrayList so it's mutable
List<Binding>bindings=newArrayList(originalPolicy.getBindingsList ());
// Add condition to a binding
Binding .BuildernewBindingBuilder=
Binding .newBuilder()
.setRole(role)
.setMembers(Arrays.asList(member))
.setCondition(conditionBuilder.build());
bindings.add(newBindingBuilder.build());
// Update policy with new conditional binding
Policy .BuilderupdatedPolicyBuilder=originalPolicy.toBuilder ();
updatedPolicyBuilder.setBindings(bindings).setVersion(3);
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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// The role to grant
// const roleName = 'roles/storage.objectViewer';
// The members to grant the new role to
// const members = [
// 'user:jdoe@example.com',
// 'group:admins@example.com',
// ];
// Create a condition
// const title = 'Title';
// const description = 'Description';
// const expression = 'resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")';
// Imports the Google Cloud client library
const{Storage}=require('@google-cloud/storage');
// Creates a client
conststorage=newStorage();
asyncfunctionaddBucketConditionalBinding(){
// Get a reference to a Google Cloud Storage bucket
constbucket=storage.bucket(bucketName);
// Gets and updates the bucket's IAM policy
const[policy]=awaitbucket.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
awaitbucket.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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

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.
 * (e.g. 'my-bucket')
 * @param string $role The role that will be given to members in this binding.
 * (e.g. 'roles/storage.objectViewer')
 * @param string[] $members The member(s) associated with this binding.
 * (e.g. ['group:example@google.com'])
 * @param string $title The title of the condition. (e.g. 'Title')
 * @param string $description The description of the condition.
 * (e.g. 'Condition Description')
 * @param string $expression The condition specified in CEL expression language.
 * (e.g. 'resource.name.startsWith("projects/_/buckets/bucket-name/objects/prefix-a-")')
 *
 * To see how to express a condition in CEL, visit:
 * @see https://cloud.google.com/storage/docs/access-control/iam#conditions.
 */
function add_bucket_conditional_iam_binding(string $bucketName, string $role, array $members, string $title, string $description, string $expression): void
{
 $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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

fromgoogle.cloudimport storage
defadd_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(f"Added the following member(s) with role {role} to {bucket_name}:")
 for member in members:
 print(f" {member}")
 print("with condition:")
 print(f" Title: {title}")
 print(f" Description: {description}")
 print(f" Expression: {expression}")

Ruby

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

defadd_bucket_conditional_iam_bindingbucket_name:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
require"google/cloud/storage"
storage=Google::Cloud::Storage .new
bucket=storage.bucketbucket_name
role="roles/storage.objectViewer"
member="group:example@google.com"
title="Title"
description="Description"
expression="resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")"
bucket.policy requested_policy_version:3do|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}"
end

REST APIs

JSON

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

  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 $(gcloud auth print-access-token)'> tmp-policy.json

    Where BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.

  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": [
     "PRINCIPAL_IDENTIFIER"
     ],
     "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.objectViewer.

    • PRINCIPAL_IDENTIFIER identifies who the condition applies to. For example, user:jeffersonloveshiking@gmail.com. For a list of principal identifier formats, see Principal identifiers.

    • 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月01日T00: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.

    Don't 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 $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    Where BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.

Remove a condition from a bucket

Console

  1. In the Google Cloud console, go to the Cloud Storage Buckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket that you want to remove a condition from.

  3. In the Bucket details page, click the Permissions tab.

    The IAM policy that applies to the bucket appears in the Permissions section.

  4. Click the Edit icon for the principal associated with the condition.

  5. In the Edit access overlay that appears, click the name of the condition you want to delete.

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

  7. Click Save.

To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, see Troubleshooting.

Command line

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

    gcloud storage buckets get-iam-policy 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 buckets set-iam-policy to set the modified IAM policy on the bucket.

    gcloud storage buckets set-iam-policy gs://BUCKET_NAME tmp-policy.json

Code samples

C++

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

namespacegcs=::google::cloud::storage;
using::google::cloud::StatusOr;
[](gcs::Clientclient,std::stringconst&bucket_name,
std::stringconst&role,std::stringconst&condition_title,
std::stringconst&condition_description,
std::stringconst&condition_expression){
autopolicy=client.GetNativeBucketIamPolicy(
bucket_name,gcs::RequestedPolicyVersion(3));
if(!policy)throwstd::move(policy).status();
policy->set_version(3);
auto&bindings=policy->bindings();
autoe=std::remove_if(
bindings.begin(),bindings.end(),
[role,condition_title,condition_description,
condition_expression](gcs::NativeIamBindingb){
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);
autoupdated=client.SetNativeBucketIamPolicy(bucket_name,*policy);
if(!updated)throwstd::move(updated).status();
std::cout << "Conditional binding was removed.\n";
}

C#

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.


usingGoogle.Apis.Storage.v1.Data;
usingGoogle.Cloud.Storage.V1 ;
usingSystem;
usingSystem.Linq;
publicclassRemoveBucketConditionalIamBindingSample
{
publicPolicyRemoveBucketConditionalIamBinding(
stringbucketName="your-unique-bucket-name",
stringrole="roles/storage.objectViewer",
stringtitle="title",
stringdescription="description",
stringexpression="resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")")
{
varstorage=StorageClient .Create ();
varpolicy=storage.GetBucketIamPolicy(bucketName,newGetBucketIamPolicyOptions
{
RequestedPolicyVersion=3
});
// Set the policy schema version. For more information, please refer to https://cloud.google.com/iam/docs/policies#versions.
policy.Version=3;
varbindingsToRemove=policy.Bindings.Where(binding=>binding.Role==role
 && binding.Condition!=null
 && binding.Condition.Title==title
 && binding.Condition.Description==description
 && binding.Condition.Expression==expression).ToList();
if(bindingsToRemove.Count() > 0)
{
foreach(varbindinginbindingsToRemove)
{
policy.Bindings.Remove(binding);
}
// Set the modified IAM policy to be the current IAM policy.
policy=storage.SetBucketIamPolicy(bucketName,policy);
Console.WriteLine("Conditional Binding was removed.");
}
else
{
Console.WriteLine("No matching conditional binding found.");
}
returnpolicy;
}
}

Go

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

import(
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/storage"
)
// removeBucketConditionalIAMBinding removes bucket conditional IAM binding.
funcremoveBucketConditionalIAMBinding(wio.Writer ,bucketName,role,title,description,expressionstring)error{
// bucketName := "bucket-name"
// role := "bucket-level IAM role"
// title := "condition title"
// description := "condition description"
// expression := "condition expression"
ctx:=context.Background()
client,err:=storage.NewClient(ctx)
iferr!=nil{
returnfmt.Errorf("storage.NewClient: %w",err)
}
deferclient.Close()
ctx,cancel:=context.WithTimeout(ctx,time.Second*10)
defercancel()
bucket:=client.Bucket (bucketName)
policy,err:=bucket.IAM ().V3().Policy(ctx)
iferr!=nil{
returnfmt.Errorf("Bucket(%q).IAM().V3().Policy: %w",bucketName,err)
}
// Find the index of the binding matching inputs.
i:=-1
forj,binding:=rangepolicy.Bindings{
ifbinding.Role==role && binding.Condition!=nil{
condition:=binding.Condition
ifcondition.Title==title&&
condition.Description==description&&
condition.Expression==expression{
i=j
}
}
}
ifi==-1{
returnfmt.Errorf("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:]...)
iferr:=bucket.IAM ().V3().SetPolicy(ctx,policy);err!=nil{
returnfmt.Errorf("Bucket(%q).IAM().V3().SetPolicy: %w",bucketName,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.
fmt.Fprintln(w,"Conditional binding was removed")
returnnil
}

Java

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.


importcom.google.cloud.Binding ;
importcom.google.cloud.Condition ;
importcom.google.cloud.Policy ;
importcom.google.cloud.storage.Storage ;
importcom.google.cloud.storage.StorageOptions ;
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.List;
publicclass RemoveBucketIamConditionalBinding{
/** Example of removing a conditional binding to the Bucket-level IAM */
publicstaticvoidremoveBucketIamConditionalBinding(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=newArrayList(originalPolicy.getBindingsList ());
// Create a condition to compare against
Condition .BuilderconditionBuilder=Condition .newBuilder();
conditionBuilder.setTitle("Title");
conditionBuilder.setDescription("Description");
conditionBuilder.setExpression(
"resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")");
Iteratoriterator=bindings.iterator();
while(iterator.hasNext()){
Binding binding=(Binding )iterator.next();
booleanfoundRole=binding.getRole ().equals(role);
booleanconditionsEqual=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 .BuilderupdatedPolicyBuilder=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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// The role to grant
// const roleName = 'roles/storage.objectViewer';
// The members to grant the new role to
// const members = [
// 'user:jdoe@example.com',
// 'group:admins@example.com',
// ];
// Create a condition
// const title = 'Title';
// const description = 'Description';
// const expression = 'resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")';
// Imports the Google Cloud client library
const{Storage}=require('@google-cloud/storage');
// Creates a client
conststorage=newStorage();
asyncfunctionremoveBucketConditionalBinding(){
// Get a reference to a Google Cloud Storage bucket
constbucket=storage.bucket(bucketName);
// Gets and updates the bucket's IAM policy
const[policy]=awaitbucket.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.
constindex=policy.bindings .findIndex(
binding=>
binding.role===roleName&&
binding.condition&&
binding.condition .title===title&&
binding.condition .description===description&&
binding.condition .expression===expression
);
constbinding=policy.bindings [index];
if(binding){
policy.bindings .splice(index,1);
// Updates the bucket's IAM policy
awaitbucket.iam .setPolicy (policy);
console.log('Conditional Binding was removed.');
}else{
// No matching role-member group with specific condition were found
thrownewError('No matching binding group found.');
}
}
removeBucketConditionalBinding().catch(console.error);

PHP

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

use Google\Cloud\Storage\StorageClient;
/**
 * Removes a conditional IAM binding from a bucket's IAM policy.
 *
 * To see how to express a condition in CEL, visit:
 * @see https://cloud.google.com/storage/docs/access-control/iam#conditions.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 * (e.g. 'my-bucket')
 * @param string $role the role that will be given to members in this binding.
 * (e.g. 'roles/storage.objectViewer')
 * @param string $title The title of the condition. (e.g. 'Title')
 * @param string $description The description of the condition.
 * (e.g. 'Condition Description')
 * @param string $expression Te condition specified in CEL expression language.
 * (e.g. 'resource.name.startsWith("projects/_/buckets/bucket-name/objects/prefix-a-")')
 */
function remove_bucket_conditional_iam_binding(string $bucketName, string $role, string $title, string $description, string $expression): void
{
 $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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

fromgoogle.cloudimport storage
defremove_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.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

defremove_bucket_conditional_iam_bindingbucket_name:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
require"google/cloud/storage"
storage=Google::Cloud::Storage .new
bucket=storage.bucketbucket_name
role="roles/storage.objectViewer"
title="Title"
description="Description"
expression="resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")"
bucket.policy requested_policy_version:3do|policy|
policy.version =3
binding_to_remove=nil
policy.bindings .each do|b|
condition={
title:title,
description:description,
expression:expression
}
ifb.role==role && b.condition&&
b.condition .title ==title&&
b.condition .description==description&&
b.condition .expression ==expression
binding_to_remove=b
end
end
ifbinding_to_remove
policy.bindings .removebinding_to_remove
puts"Conditional Binding was removed."
else
puts"No matching conditional binding found."
end
end
end

REST APIs

JSON

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

  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 $(gcloud auth print-access-token)'> tmp-policy.json

    Where BUCKET_NAME is the name of the bucket you are granting access to. For example, my-bucket.

  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 $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

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

Best practices

You should set the minimum role needed to give the principal the required access. For example, if a team member only needs to read objects stored in a bucket, grant them the Storage Object Viewer (roles/storage.objectViewer) role instead of the Storage Object Admin (roles/storage.objectAdmin) role. Similarly, if the team member needs full control of objects in the bucket but not the bucket itself, grant them the Storage Object Admin (roles/storage.objectAdmin) role instead of the Storage Admin (roles/storage.admin) role.

What's next

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025年11月06日 UTC.