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

  1. Open the Stackdriver Metrics Explorer.

    Open the Metrics Explorer

    If you haven't used Stackdriver previously, click on the Create a workspace button, and create a workspace for the project that contains your bucket.

  2. In the Find resource type and metric text box, enter storage.googleapis.com/authz/acl_operations_count.

    The associated chart displays the ACL operations you are using. If the metric does not exist, there is no recent ACL usage for your project.

  3. (Optional) To group the data by bucket and ACL operation, select acl_operation for Group By and sum for Aggregator.

See the Stackdriver metrics documentation for a complete list of available metrics and Metrics, time series, and resources for more information about using the Metrics Explorer.

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 Simplify access control with uniform bucket-level access text box, click Enable.

  5. In the confirmation dialog that appears, click Enable.

gsutil

Use the on option in a uniformbucketlevelaccess set command, replacing [VALUES_IN_BRACKETS] with the appropriate values:

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

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 .

bucket := c.Bucket(bucketName)
enableUniformBucketLevelAccess := storage.BucketAttrsToUpdate{
	UniformBucketLevelAccess: &storage.UniformBucketLevelAccess{
		Enabled: true,
	},
}
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 .

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

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

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

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

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

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 .

# bucket_name = "my-bucket"

storage_client = storage.Client()
bucket = storage_client.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, replacing [VALUES_IN_BRACKETS] with the appropriate values:

    {
      "iamConfiguration": {
          "uniformbucketlevelaccess": {
            "enabled": true
          }
      }
    }
  3. Use cURL to call the JSON API with a PATCH Bucket request, replacing [VALUES_IN_BRACKETS] with the appropriate values:

    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"

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 Columns drop-down menu, make sure Access control model is checked.

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

gsutil

Use the uniformbucketlevelaccess get command, replacing [VALUES_IN_BRACKETS] with the appropriate values:

gsutil uniformbucketlevelaccess get gs://[BUCKET_NAME]/

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 .

namespace gcs = google::cloud::storage;
using google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name);

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

  if (bucket_metadata->has_iam_configuration() &&
      bucket_metadata->iam_configuration()
          .uniform_bucket_level_access.has_value()) {
    gcs::UniformBucketLevelAccess uniform_bucket_level_access =
        *bucket_metadata->iam_configuration().uniform_bucket_level_access;

    std::cout << "Uniform Bucket Level Access is enabled for "
              << bucket_metadata->name() << "\n";
    std::cout << "Bucket will be locked on " << uniform_bucket_level_access
              << "\n";
  } else {
    std::cout << "Uniform Bucket Level Access is not enabled for "
              << bucket_metadata->name() << "\n";
  }
}

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 .

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 .

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

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

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

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

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 .

# 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, replacing [VALUES_IN_BRACKETS] with the appropriate values:

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

    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

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 Object-level permissions are disabled text box, click Enable.

  5. In the confirmation dialog that appears, click Enable.

gsutil

Use the off option in a uniformbucketlevelaccess set command, replacing [VALUES_IN_BRACKETS] with the appropriate values:

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

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 .

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{false, {}};
  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 disabled Uniform Bucket Level Access on bucket "
            << updated_metadata->name() << "\n";
}

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 .

bucket := c.Bucket(bucketName)
disableUniformBucketLevelAccess := storage.BucketAttrsToUpdate{
	UniformBucketLevelAccess: &storage.UniformBucketLevelAccess{
		Enabled: false,
	},
}
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 .

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

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

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

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

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 .

# bucket_name = "my-bucket"

storage_client = storage.Client()
bucket = storage_client.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, replacing [VALUES_IN_BRACKETS] with the appropriate values:

    {
      "iamConfiguration": {
          "uniformbucketlevelaccess": {
            "enabled": false
          }
      }
    }
  3. Use cURL to call the JSON API with a PATCH Bucket request, replacing [VALUES_IN_BRACKETS] with the appropriate values:

    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"

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

Oliko tästä sivusta apua? Kerro mielipiteesi

Palautteen aihe:

Tämä sivu
Cloud Storage
Tarvitsetko apua? Siirry tukisivullemme.