Add conditional role binding

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

An example of how to set a startsWith condition with the client libraries.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample


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

//! [native add bucket conditional iam binding]
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::move(policy).status();

      role, {member},
      gcs::NativeExpression(condition_expression, condition_title,

  auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
  if (!updated) throw std::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";
//! [native add bucket conditional iam binding]


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

using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class AddBucketConditionalIamBindingSample
    /// <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>
    public Policy AddBucketConditionalIamBinding(
        string bucketName = "your-unique-bucket-name",
        string role = "roles/storage.objectViewer",
        string member = "",
        string title = "title",
        string description = "description",
        string expression = "\"projects/_/buckets/bucket-name/objects/prefix-a-\")")
        var storage = StorageClient.Create();
        var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions
            RequestedPolicyVersion = 3
        // Set the policy schema version. For more information, please refer to
        policy.Version = 3;
        Policy.BindingsData bindingToAdd = new Policy.BindingsData
            Role = role,
            Members = new List<string> { member },
            Condition = new Expr
                Title = title,
                Description = description,
                Expression = expression


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


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.


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

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:
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

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

    String role = "roles/storage.objectViewer";
    String member = "";

    // Create a condition
    String conditionTitle = "Title";
    String conditionDescription = "Description";
    String conditionExpression =
    Condition.Builder conditionBuilder = Condition.newBuilder();

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

    // Add condition to a binding
    Binding.Builder newBindingBuilder =

    // Update policy with new conditional binding
    Policy.Builder updatedPolicyBuilder = originalPolicy.toBuilder();


        "Added %s with role %s to %s with condition %s %s %s\n",
        member, role, bucketName, conditionTitle, conditionDescription, conditionExpression);


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

 * 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 = [
//   '',
//   '',
// ];

// Create a condition
// const title = 'Title';
// const description = 'Description';
// const expression = '\"projects/_/buckets/bucket-name/objects/prefix-a-\")';

// 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
    role: roleName,
    members: members,
    condition: {
      title: title,
      description: description,
      expression: expression,

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

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



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.
 *        (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. [''])
 * @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. '"projects/_/buckets/bucket-name/objects/prefix-a-")')
 * To see how to express a condition in CEL, visit:
 * @see
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,


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


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

from 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:}"
    # 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

            "role": role,
            "members": members,
            "condition": {
                "title": title,
                "description": description,
                "expression": expression,


    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}")


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

def add_bucket_conditional_iam_binding bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage =
  bucket = storage.bucket bucket_name

  role        = "roles/storage.objectViewer"
  member      = ""
  title       = "Title"
  description = "Description"
  expression  = "\"projects/_/buckets/bucket-name/objects/prefix-a-\")"

  bucket.policy requested_policy_version: 3 do |policy|
    policy.version = 3
      role:      role,
      members:   member,
      condition: {
        title:       title,
        description: description,
        expression:  expression

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.