Using uniform bucket-level access

This page shows you how to enable, disable and check the status of uniform bucket-level access on a bucket in Cloud Storage. For details about this feature, see Uniform bucket-level access.

Prerequisites

Before using this feature in Cloud Storage, you should:

  1. Have sufficient permission to view and update buckets in Cloud Storage:

    • If you own the project that contains the bucket, you most likely have the necessary permissions.

    • You should have the storage.buckets.update and storage.buckets.get IAM permissions on the relevant bucket. See Using IAM Permissions for instructions on how to get a role, such as roles/storage.admin, that has these permissions.

Check for ACL usage

Before you enable uniform bucket-level access, use Stackdriver to ensure your bucket is not using ACLs for any workflows. For more information, see Check object ACL usage.

Console

To view the metrics for a monitored resource using Metrics Explorer, do the following:

  1. In the Google Cloud Console, go to Monitoring or use the following button:
    Go to Monitoring
  2. If Metrics Explorer is shown in the navigation pane, click Metrics Explorer. Otherwise, select Resources and then select Metrics Explorer.
  3. Ensure Metric is the selected tab.
  4. Click in the box labeled Find resource type and metric, and then select from the menu or enter the name for the resource and metric. Use the following information to complete the fields for this text box:
    1. For the Resource, select or enter gcs_bucket.
    2. For the Metric, select or enter ACLs usage.
    The fully qualified name for this monitored resource is storage.googleapis.com/authz/acl_operations_count.
  5. Use the Filter, Group By, and Aggregation menus to modify how the data is displayed. For example, to group the data by bucket and ACL operation, select acl_operation for Group By and sum for Aggregator. For more information, see Selecting metrics - additional configuration.

See storage for a complete list of metrics available for Cloud Storage. For information about time series, see Metrics, time series, and resources.

JSON API

  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 Monitoring JSON API:

curl \
'https://monitoring.googleapis.com/v3/projects/[PROJECT_ID]/timeSeries?filter=metric.type%20%3D%20%22storage.googleapis.com%2Fauthz%2Facl_operations_count%22&interval.endTime=[END_TIME]&interval.startTime=[START_TIME]' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json'

Where:

  • [PROJECT_ID] is the project ID or number for which you want to view ACL usage. For example, my-project.
  • [END_TIME] is the end of the time range for which you want to view ACL usage. For example, 2014-11-02T15:01:23.045123456Z.
  • [START_TIME] is the start of the time range for which you want to view ACL usage. For example, 2014-10-02T15:01:23.045123456Z.
  • [YOUR_ACCESS_TOKEN] is the access token you generated in Step 1.

If the request returns an empty object {}, there is no recent ACL usage for your project.

Enable uniform bucket-level access

To enable uniform bucket-level access on your bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the desired bucket.

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

  4. In the text box that starts with This bucket uses fine-grained access control..., click Edit.

  5. In the pop-up menu that appears, select Uniform.

  6. Click Save.

gsutil

Use the on option in a uniformbucketlevelaccess set command:

gsutil uniformbucketlevelaccess set on gs://[BUCKET_NAME]/

where [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.

If successful, the response looks like:

Enabling uniform bucket-level access for gs://test-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 bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.uniform_bucket_level_access =
      gcs::UniformBucketLevelAccess{true, {}};
  StatusOr<gcs::BucketMetadata> updated_metadata = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetIamConfiguration(
                       std::move(configuration)));

  if (!updated_metadata) {
    throw std::runtime_error(updated_metadata.status().message());
  }

  std::cout << "Successfully enabled Uniform Bucket Level Access on bucket "
            << updated_metadata->name() << "\n";
}

C#

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

        private void EnableUniformBucketLevelAccess(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            bucket.IamConfiguration.UniformBucketLevelAccess.Enabled = true;
            bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
            {
                // Use IfMetagenerationMatch to avoid race conditions.
                IfMetagenerationMatch = bucket.Metageneration,
            });

            Console.WriteLine($"Uniform bucket-level access was enabled for {bucketName}.");
        }

Go

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

ctx := context.Background()

bucket := c.Bucket(bucketName)
enableUniformBucketLevelAccess := storage.BucketAttrsToUpdate{
	UniformBucketLevelAccess: &storage.UniformBucketLevelAccess{
		Enabled: true,
	},
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, enableUniformBucketLevelAccess); err != nil {
	return err
}

Java

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

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

BucketInfo.IamConfiguration iamConfiguration =
    BucketInfo.IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build();
Bucket bucket =
    storage.update(
        BucketInfo.newBuilder(bucketName).setIamConfiguration(iamConfiguration).build());

System.out.println("Uniform bucket-level access was enabled for " + 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';

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

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

// Enables uniform bucket-level access for the bucket
async function enableUniformBucketLevelAccess() {
  await storage.bucket(bucketName).setMetadata({
    iamConfiguration: {
      uniformBucketLevelAccess: {
        enabled: true,
      },
    },
  });

  console.log(`Uniform bucket-level access was enabled for ${bucketName}.`);
}

enableUniformBucketLevelAccess().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Enable uniform bucket-level access.
 *
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function enable_uniform_bucket_level_access($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'iamConfiguration' => [
            'uniformBucketLevelAccess' => [
                'enabled' => true
            ],
        ]
    ]);
    printf('Uniform bucket-level access was enabled for %s' . PHP_EOL, $bucketName);
}

Python

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

from google.cloud import storage


def enable_uniform_bucket_level_access(bucket_name):
    """Enable uniform bucket-level access for a bucket"""
    # bucket_name = "my-bucket"

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

    bucket.iam_configuration.uniform_bucket_level_access_enabled = True
    bucket.patch()

    print(
        "Uniform bucket-level access was enabled for {}.".format(bucket.name)
    )

Ruby

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

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

bucket.uniform_bucket_level_access = true

puts "Uniform bucket-level access was enabled for #{bucket_name}."

REST APIs

JSON API

  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:

    {
      "iamConfiguration": {
          "uniformbucketlevelaccess": {
            "enabled": true
          }
      }
    }
  3. Use cURL to call the JSON API with a PATCH Bucket request:

    curl -X PATCH --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]?fields=iamConfiguration"

    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 relevant bucket. For example, my-bucket.

XML API

The XML API cannot be used to work with uniform bucket-level access. Use one of the other Cloud Storage tools, such as gsutil, instead.

View uniform bucket-level access status

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the Column display options menu (Column options icon.), make sure Access control is checked.

  3. In the list of buckets, the uniform bucket-level access status of each bucket is found in the Access control column.

gsutil

Use the uniformbucketlevelaccess get command:

gsutil uniformbucketlevelaccess get gs://[BUCKET_NAME]/

where [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.

If uniform bucket-level access is enabled, the response looks like:

Uniform bucket-level access setting for gs://[BUCKET_NAME]/:
    Enabled: True
    LockedTime: [LOCK_DATE] 

Code samples

C++

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

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 bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.uniform_bucket_level_access =
      gcs::UniformBucketLevelAccess{true, {}};
  StatusOr<gcs::BucketMetadata> updated_metadata = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetIamConfiguration(
                       std::move(configuration)));

  if (!updated_metadata) {
    throw std::runtime_error(updated_metadata.status().message());
  }

  std::cout << "Successfully enabled Uniform Bucket Level Access on bucket "
            << updated_metadata->name() << "\n";
}

C#

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

        private void EnableUniformBucketLevelAccess(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            bucket.IamConfiguration.UniformBucketLevelAccess.Enabled = true;
            bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
            {
                // Use IfMetagenerationMatch to avoid race conditions.
                IfMetagenerationMatch = bucket.Metageneration,
            });

            Console.WriteLine($"Uniform bucket-level access was enabled for {bucketName}.");
        }

Go

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

ctx := context.Background()

bucket := c.Bucket(bucketName)
enableUniformBucketLevelAccess := storage.BucketAttrsToUpdate{
	UniformBucketLevelAccess: &storage.UniformBucketLevelAccess{
		Enabled: true,
	},
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, enableUniformBucketLevelAccess); err != nil {
	return err
}

Java

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

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

BucketInfo.IamConfiguration iamConfiguration =
    BucketInfo.IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build();
Bucket bucket =
    storage.update(
        BucketInfo.newBuilder(bucketName).setIamConfiguration(iamConfiguration).build());

System.out.println("Uniform bucket-level access was enabled for " + 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';

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

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

// Enables uniform bucket-level access for the bucket
async function enableUniformBucketLevelAccess() {
  await storage.bucket(bucketName).setMetadata({
    iamConfiguration: {
      uniformBucketLevelAccess: {
        enabled: true,
      },
    },
  });

  console.log(`Uniform bucket-level access was enabled for ${bucketName}.`);
}

enableUniformBucketLevelAccess().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Enable uniform bucket-level access.
 *
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function enable_uniform_bucket_level_access($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'iamConfiguration' => [
            'uniformBucketLevelAccess' => [
                'enabled' => true
            ],
        ]
    ]);
    printf('Uniform bucket-level access was enabled for %s' . PHP_EOL, $bucketName);
}

Python

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

from google.cloud import storage


def enable_uniform_bucket_level_access(bucket_name):
    """Enable uniform bucket-level access for a bucket"""
    # bucket_name = "my-bucket"

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

    bucket.iam_configuration.uniform_bucket_level_access_enabled = True
    bucket.patch()

    print(
        "Uniform bucket-level access was enabled for {}.".format(bucket.name)
    )

Ruby

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

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

bucket.uniform_bucket_level_access = true

puts "Uniform bucket-level access was enabled for #{bucket_name}."

C#

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

        private void GetUniformBucketLevelAccess(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            var uniformBucketLevelAccess = bucket.IamConfiguration.UniformBucketLevelAccess;

            bool? enabledOrNull = uniformBucketLevelAccess?.Enabled;
            bool uniformBucketLevelAccessEnabled =
                enabledOrNull.HasValue ? enabledOrNull.Value : false;
            if (uniformBucketLevelAccessEnabled)
            {
                Console.WriteLine($"Uniform bucket-level access is enabled for {bucketName}.");
                Console.WriteLine(
                    $"Uniform bucket-level access will be locked on {uniformBucketLevelAccess.LockedTime}.");
            }
            else
            {
                Console.WriteLine($"Uniform bucket-level access is not enabled for {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()
attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return nil, err
}
uniformBucketLevelAccess := attrs.UniformBucketLevelAccess
if uniformBucketLevelAccess.Enabled {
	log.Printf("Uniform bucket-level access is enabled for %q.\n",
		attrs.Name)
	log.Printf("Bucket will be locked on %q.\n",
		uniformBucketLevelAccess.LockedTime)
} else {
	log.Printf("Uniform bucket-level access is not enabled for %q.\n",
		attrs.Name)
}

Java

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

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

Bucket bucket = storage.get(bucketName, BucketGetOption.fields(BucketField.IAMCONFIGURATION));
BucketInfo.IamConfiguration iamConfiguration = bucket.getIamConfiguration();

Boolean enabled = iamConfiguration.isUniformBucketLevelAccessEnabled();
Date lockedTime = new Date(iamConfiguration.getUniformBucketLevelAccessLockedTime());

if (enabled != null && enabled) {
  System.out.println("Uniform bucket-level access is enabled for " + bucketName);
  System.out.println("Bucket will be locked on " + lockedTime);
} else {
  System.out.println("Uniform bucket-level access is disabled for " + 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';

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

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

async function getUniformBucketLevelAccess() {
  // Gets Bucket Metadata and checks if uniform bucket-level access is enabled.
  const [metadata] = await storage.bucket(bucketName).getMetadata();

  if (metadata.iamConfiguration) {
    const uniformBucketLevelAccess =
      metadata.iamConfiguration.uniformBucketLevelAccess;
    console.log(`Uniform bucket-level access is enabled for ${bucketName}.`);
    console.log(
      `Bucket will be locked on ${uniformBucketLevelAccess.lockedTime}.`
    );
  } else {
    console.log(
      `Uniform bucket-level access is not enabled for ${bucketName}.`
    );
  }
}

getUniformBucketLevelAccess().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Enable uniform bucket-level access.
 *
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function get_uniform_bucket_level_access($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucketInformation = $bucket->info();
    $ubla = $bucketInformation['iamConfiguration']['uniformBucketLevelAccess'];
    if ($ubla['enabled']) {
        printf('Uniform bucket-level access is enabled for %s' . PHP_EOL, $bucketName);
        printf('Uniform bucket-level access will be locked on %s' . PHP_EOL, $ubla['LockedTime']);
    } else {
        printf('Uniform bucket-level access is disabled for %s' . PHP_EOL, $bucketName);
    }
}

Python

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

from google.cloud import storage


def get_uniform_bucket_level_access(bucket_name):
    """Get uniform bucket-level access for a bucket"""
    # bucket_name = "my-bucket"

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

    if iam_configuration.uniform_bucket_level_access_enabled:
        print(
            "Uniform bucket-level access is enabled for {}.".format(
                bucket.name
            )
        )
        print(
            "Bucket will be locked on {}.".format(
                iam_configuration.uniform_bucket_level_locked_time
            )
        )
    else:
        print(
            "Uniform bucket-level access is disabled for {}.".format(
                bucket.name
            )
        )

Ruby

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

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

if bucket.uniform_bucket_level_access?
  puts "Uniform bucket-level access is enabled for #{bucket_name}."
  puts "Bucket will be locked on #{bucket.uniform_bucket_level_access_locked_at}."
else
  puts "Uniform bucket-level access is disabled for #{bucket_name}."
end

REST APIs

JSON API

  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 Bucket request that includes the desired fields:

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

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.

    If the bucket has uniform bucket-level access enabled, the response looks like the following example:

    {
      "iamConfiguration": {
          "uniformbucketlevelaccess": {
            "enabled": true,
            "lockedTime": "[LOCK_DATE]"
          }
        }
      }

XML API

The XML API cannot be used to work with uniform bucket-level access. Use one of the other Cloud Storage tools, such as gsutil, instead.

Disable uniform bucket-level access

You must remove all Cloud IAM conditions from the bucket's Cloud IAM policy before you can disable uniform bucket-level access.

To disable uniform bucket-level access on your bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the desired bucket.

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

  4. In the text box that starts with This bucket uses uniform bucket-level access control..., click Edit. Note that the text box disappears 90 days after you enable uniform bucket-level access.

  5. In the pop-up menu that appears, select Fine-grained.

  6. Click Save.

gsutil

Use the off option in a uniformbucketlevelaccess set command:

gsutil uniformbucketlevelaccess set off gs://[BUCKET_NAME]/

where [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.

If successful, the response looks like:

Disabling uniform bucket-level access for gs://test-bucket/...

Code samples

C++

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

C++

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

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 bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.uniform_bucket_level_access =
      gcs::UniformBucketLevelAccess{true, {}};
  StatusOr<gcs::BucketMetadata> updated_metadata = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetIamConfiguration(
                       std::move(configuration)));

  if (!updated_metadata) {
    throw std::runtime_error(updated_metadata.status().message());
  }

  std::cout << "Successfully enabled Uniform Bucket Level Access on bucket "
            << updated_metadata->name() << "\n";
}

C#

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

        private void EnableUniformBucketLevelAccess(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            bucket.IamConfiguration.UniformBucketLevelAccess.Enabled = true;
            bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
            {
                // Use IfMetagenerationMatch to avoid race conditions.
                IfMetagenerationMatch = bucket.Metageneration,
            });

            Console.WriteLine($"Uniform bucket-level access was enabled for {bucketName}.");
        }

Go

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

ctx := context.Background()

bucket := c.Bucket(bucketName)
enableUniformBucketLevelAccess := storage.BucketAttrsToUpdate{
	UniformBucketLevelAccess: &storage.UniformBucketLevelAccess{
		Enabled: true,
	},
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, enableUniformBucketLevelAccess); err != nil {
	return err
}

Java

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

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

BucketInfo.IamConfiguration iamConfiguration =
    BucketInfo.IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build();
Bucket bucket =
    storage.update(
        BucketInfo.newBuilder(bucketName).setIamConfiguration(iamConfiguration).build());

System.out.println("Uniform bucket-level access was enabled for " + 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';

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

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

// Enables uniform bucket-level access for the bucket
async function enableUniformBucketLevelAccess() {
  await storage.bucket(bucketName).setMetadata({
    iamConfiguration: {
      uniformBucketLevelAccess: {
        enabled: true,
      },
    },
  });

  console.log(`Uniform bucket-level access was enabled for ${bucketName}.`);
}

enableUniformBucketLevelAccess().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Enable uniform bucket-level access.
 *
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function enable_uniform_bucket_level_access($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'iamConfiguration' => [
            'uniformBucketLevelAccess' => [
                'enabled' => true
            ],
        ]
    ]);
    printf('Uniform bucket-level access was enabled for %s' . PHP_EOL, $bucketName);
}

Python

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

from google.cloud import storage


def enable_uniform_bucket_level_access(bucket_name):
    """Enable uniform bucket-level access for a bucket"""
    # bucket_name = "my-bucket"

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

    bucket.iam_configuration.uniform_bucket_level_access_enabled = True
    bucket.patch()

    print(
        "Uniform bucket-level access was enabled for {}.".format(bucket.name)
    )

Ruby

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

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

bucket.uniform_bucket_level_access = true

puts "Uniform bucket-level access was enabled for #{bucket_name}."

C#

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

        private void GetUniformBucketLevelAccess(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            var uniformBucketLevelAccess = bucket.IamConfiguration.UniformBucketLevelAccess;

            bool? enabledOrNull = uniformBucketLevelAccess?.Enabled;
            bool uniformBucketLevelAccessEnabled =
                enabledOrNull.HasValue ? enabledOrNull.Value : false;
            if (uniformBucketLevelAccessEnabled)
            {
                Console.WriteLine($"Uniform bucket-level access is enabled for {bucketName}.");
                Console.WriteLine(
                    $"Uniform bucket-level access will be locked on {uniformBucketLevelAccess.LockedTime}.");
            }
            else
            {
                Console.WriteLine($"Uniform bucket-level access is not enabled for {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()
attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return nil, err
}
uniformBucketLevelAccess := attrs.UniformBucketLevelAccess
if uniformBucketLevelAccess.Enabled {
	log.Printf("Uniform bucket-level access is enabled for %q.\n",
		attrs.Name)
	log.Printf("Bucket will be locked on %q.\n",
		uniformBucketLevelAccess.LockedTime)
} else {
	log.Printf("Uniform bucket-level access is not enabled for %q.\n",
		attrs.Name)
}

Java

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

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

Bucket bucket = storage.get(bucketName, BucketGetOption.fields(BucketField.IAMCONFIGURATION));
BucketInfo.IamConfiguration iamConfiguration = bucket.getIamConfiguration();

Boolean enabled = iamConfiguration.isUniformBucketLevelAccessEnabled();
Date lockedTime = new Date(iamConfiguration.getUniformBucketLevelAccessLockedTime());

if (enabled != null && enabled) {
  System.out.println("Uniform bucket-level access is enabled for " + bucketName);
  System.out.println("Bucket will be locked on " + lockedTime);
} else {
  System.out.println("Uniform bucket-level access is disabled for " + 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';

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

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

async function getUniformBucketLevelAccess() {
  // Gets Bucket Metadata and checks if uniform bucket-level access is enabled.
  const [metadata] = await storage.bucket(bucketName).getMetadata();

  if (metadata.iamConfiguration) {
    const uniformBucketLevelAccess =
      metadata.iamConfiguration.uniformBucketLevelAccess;
    console.log(`Uniform bucket-level access is enabled for ${bucketName}.`);
    console.log(
      `Bucket will be locked on ${uniformBucketLevelAccess.lockedTime}.`
    );
  } else {
    console.log(
      `Uniform bucket-level access is not enabled for ${bucketName}.`
    );
  }
}

getUniformBucketLevelAccess().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Enable uniform bucket-level access.
 *
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function get_uniform_bucket_level_access($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucketInformation = $bucket->info();
    $ubla = $bucketInformation['iamConfiguration']['uniformBucketLevelAccess'];
    if ($ubla['enabled']) {
        printf('Uniform bucket-level access is enabled for %s' . PHP_EOL, $bucketName);
        printf('Uniform bucket-level access will be locked on %s' . PHP_EOL, $ubla['LockedTime']);
    } else {
        printf('Uniform bucket-level access is disabled for %s' . PHP_EOL, $bucketName);
    }
}

Python

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

from google.cloud import storage


def get_uniform_bucket_level_access(bucket_name):
    """Get uniform bucket-level access for a bucket"""
    # bucket_name = "my-bucket"

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

    if iam_configuration.uniform_bucket_level_access_enabled:
        print(
            "Uniform bucket-level access is enabled for {}.".format(
                bucket.name
            )
        )
        print(
            "Bucket will be locked on {}.".format(
                iam_configuration.uniform_bucket_level_locked_time
            )
        )
    else:
        print(
            "Uniform bucket-level access is disabled for {}.".format(
                bucket.name
            )
        )

Ruby

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

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

if bucket.uniform_bucket_level_access?
  puts "Uniform bucket-level access is enabled for #{bucket_name}."
  puts "Bucket will be locked on #{bucket.uniform_bucket_level_access_locked_at}."
else
  puts "Uniform bucket-level access is disabled for #{bucket_name}."
end

C#

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

        private void DisableUniformBucketLevelAccess(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            bucket.IamConfiguration.UniformBucketLevelAccess.Enabled = false;
            /** THIS IS A WORKAROUND */
            bucket.IamConfiguration.BucketPolicyOnly.Enabled = false;
            /** THIS IS A WORKAROUND */
            bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
            {
                // Use IfMetagenerationMatch to avoid race conditions.
                IfMetagenerationMatch = bucket.Metageneration,
            });

            Console.WriteLine($"Uniform bucket-level access was disabled for {bucketName}.");
        }

Go

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

ctx := context.Background()

bucket := c.Bucket(bucketName)
disableUniformBucketLevelAccess := storage.BucketAttrsToUpdate{
	UniformBucketLevelAccess: &storage.UniformBucketLevelAccess{
		Enabled: false,
	},
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, disableUniformBucketLevelAccess); err != nil {
	return err
}

Java

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

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

BucketInfo.IamConfiguration iamConfiguration =
    BucketInfo.IamConfiguration.newBuilder()
        .setIsUniformBucketLevelAccessEnabled(false)
        .build();
Bucket bucket =
    storage.update(
        BucketInfo.newBuilder(bucketName).setIamConfiguration(iamConfiguration).build());

System.out.println("Uniform bucket-level access was disabled for " + 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';
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();
async function disableUniformBucketLevelAccess() {
  // Disables uniform bucket-level access for the bucket
  await storage.bucket(bucketName).setMetadata({
    iamConfiguration: {
      uniformBucketLevelAccess: {
        enabled: false,
      },
    },
  });

  console.log(`Uniform bucket-level access was disabled for ${bucketName}.`);
}

disableUniformBucketLevelAccess().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Enable uniform bucket-level access.
 *
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function disable_uniform_bucket_level_access($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'iamConfiguration' => [
            'uniformBucketLevelAccess' => [
                'enabled' => false
            ],
        ]
    ]);
    printf('Uniform bucket-level access was disabled for %s' . PHP_EOL, $bucketName);
}

Python

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

from google.cloud import storage


def disable_uniform_bucket_level_access(bucket_name):
    """Disable uniform bucket-level access for a bucket"""
    # bucket_name = "my-bucket"

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

    bucket.iam_configuration.uniform_bucket_level_access_enabled = False
    bucket.patch()

    print(
        "Uniform bucket-level access was disabled for {}.".format(bucket.name)
    )

Ruby

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

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

bucket.uniform_bucket_level_access = false

puts "Uniform bucket-level access was disabled for #{bucket_name}."

REST APIs

JSON API

  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:

    {
      "iamConfiguration": {
          "uniformbucketlevelaccess": {
            "enabled": false
          }
      }
    }
  3. Use cURL to call the JSON API with a PATCH Bucket request:

    curl -X PATCH --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]?fields=iamConfiguration"

    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 relevant bucket. For example, my-bucket.

XML API

The XML API cannot be used to work with uniform bucket-level access. Use one of the other Cloud Storage tools, such as gsutil, instead.

What's next