使用统一存储桶级访问权限

概览

本页面介绍了如何对 Cloud Storage 的存储桶启用和停用统一存储桶级访问权限,以及如何检查该功能的状态。

所需的角色

如需获得设置和管理存储桶的统一存储桶级访问权限所需的权限,请让管理员向您授予存储桶的 Storage Admin (roles/storage.admin) 角色。此预定义角色包含设置和管理统一存储桶级访问权限所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

  • storage.buckets.get
  • storage.buckets.list
    • 仅当您计划使用 Google Cloud 控制台执行本页面上的任务时,才需要此权限。
  • storage.buckets.update

您也可以使用自定义角色来获取这些权限。

如需了解如何授予存储桶的角色,请参阅将 IAM 与存储桶搭配使用

检查 ACL 使用情况

启用统一存储桶级访问权限之前,请使用 Cloud Monitoring 确保您的存储桶没有将 ACL 用于任何工作流。如需了解详情,请参阅检查对象 ACL 的使用情况

控制台

如需使用 Metrics Explorer 查看受监控资源的指标,请执行以下操作:

  1. 在 Google Cloud 控制台中,转到 Metrics Explorer 页面:

    进入 Metrics Explorer

    如果您使用搜索栏查找此页面,请选择子标题为监控的结果。

  2. 指标元素中,展开选择指标菜单,在过滤栏中输入 ACLs usage,然后使用子菜单选择一个特定资源类型和指标:
    1. 活跃资源菜单中,选择 GCS 存储桶
    2. 活跃指标类别菜单中,选择 Authz
    3. 活跃指标菜单中,选择 ACL 用量
    4. 点击应用
    此指标的完全限定名称为 storage.googleapis.com/authz/acl_operations_count
  3. 配置数据的查看方式。 例如,如需按 ACL 操作查看数据,则对于聚合元素,请将第一个菜单设置为总和,并将第二个菜单设置为 acl_operation

    如需详细了解如何配置图表,请参阅使用 Metrics Explorer 时选择指标

如需查看可用于 Cloud Storage 的指标的完整列表,请参阅 storage。如需了解时间序列,请参阅指标、时间序列和资源

JSON API

  1. 安装并初始化 gcloud CLI,以便为 Authorization 标头生成访问令牌。

    或者,您可以创建访问令牌(使用 OAuth 2.0 Playground),并将其包含在 Authorization 标头中。

  2. 使用 cURL 调用 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 $(gcloud auth print-access-token)' \
    --header 'Accept: application/json'

    其中:

    • PROJECT_ID 是您要查看其 ACL 使用情况的项目 ID 或编号,例如 my-project
    • END_TIME 是您要查看其 ACL 使用情况的时间范围的结束时间,例如 2019-11-02T15:01:23.045123456Z
    • START_TIME 是您要查看其 ACL 使用情况的时间范围的开始时间,例如 2016-10-02T15:01:23.045123456Z

如果请求返回空对象 {},则说明您的项目最近没有使用 ACL。

设置统一存储桶级访问权限

如需对存储桶启用或停用统一存储桶级访问权限,请按照以下说明操作:

控制台

  1. 在 Google Cloud 控制台中,进入 Cloud Storage 存储桶页面。

    进入“存储桶”

  2. 在存储桶列表中,找到要启用或停用统一存储桶级访问权限的存储桶,然后点击其名称。

  3. 选择页面顶部附近的权限标签。

  4. 在名为访问权限控制的字段中,点击切换到链接。

  5. 在出现的菜单中,选择统一精细

  6. 点击保存

如需了解如何在 Google Cloud 控制台中获取失败的 Cloud Storage 操作的详细错误信息,请参阅问题排查

命令行

使用 gcloud storage buckets update 命令:

gcloud storage buckets update gs://BUCKET_NAME --STATE

其中:

  • BUCKET_NAME 是相关存储桶的名称,例如 my-bucket
  • STATE 可以为 uniform-bucket-level-access 以启用统一存储桶级访问权限,或者为 no-uniform-bucket-level-access 以停用统一存储桶级访问权限。

客户端库

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

以下示例在存储桶上启用统一存储桶级访问权限:

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.uniform_bucket_level_access =
      gcs::UniformBucketLevelAccess{true, {}};
  StatusOr<gcs::BucketMetadata> updated = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetIamConfiguration(
                       std::move(configuration)));
  if (!updated) throw std::move(updated).status();

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

以下示例在存储桶上禁用统一存储桶级访问权限:

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.uniform_bucket_level_access =
      gcs::UniformBucketLevelAccess{false, {}};
  StatusOr<gcs::BucketMetadata> updated = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetIamConfiguration(
                       std::move(configuration)));
  if (!updated) throw std::move(updated).status();

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

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

以下示例在存储桶上启用统一存储桶级访问权限:


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

public class EnableUniformBucketLevelAccessSample
{
    public Bucket EnableUniformBucketLevelAccess(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.IamConfiguration.UniformBucketLevelAccess.Enabled = true;
        bucket = storage.UpdateBucket(bucket);

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

以下示例在存储桶上禁用统一存储桶级访问权限:


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

public class DisableUniformBucketLevelAccessSample
{
    public Bucket DisableUniformBucketLevelAccess(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.IamConfiguration.UniformBucketLevelAccess.Enabled = false;
        bucket.IamConfiguration.BucketPolicyOnly.Enabled = false;
        bucket = storage.UpdateBucket(bucket);

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

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

以下示例在存储桶上启用统一存储桶级访问权限:

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// enableUniformBucketLevelAccess sets uniform bucket-level access to true.
func enableUniformBucketLevelAccess(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	enableUniformBucketLevelAccess := storage.BucketAttrsToUpdate{
		UniformBucketLevelAccess: &storage.UniformBucketLevelAccess{
			Enabled: true,
		},
	}
	if _, err := bucket.Update(ctx, enableUniformBucketLevelAccess); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Uniform bucket-level access was enabled for %v\n", bucketName)
	return nil
}

以下示例在存储桶上禁用统一存储桶级访问权限:

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// disableUniformBucketLevelAccess sets uniform bucket-level access to false.
func disableUniformBucketLevelAccess(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	disableUniformBucketLevelAccess := storage.BucketAttrsToUpdate{
		UniformBucketLevelAccess: &storage.UniformBucketLevelAccess{
			Enabled: false,
		},
	}
	if _, err := bucket.Update(ctx, disableUniformBucketLevelAccess); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Uniform bucket-level access was disabled for %v\n", bucketName)
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

以下示例在存储桶上启用统一存储桶级访问权限:


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.Storage.BucketTargetOption;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

public class EnableUniformBucketLevelAccess {
  public static void enableUniformBucketLevelAccess(String projectId, String bucketName)
      throws StorageException {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    // first look up the bucket, so we will have its metageneration
    Bucket bucket = storage.get(bucketName);

    BucketInfo.IamConfiguration iamConfiguration =
        BucketInfo.IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build();

    storage.update(
        bucket
            .toBuilder()
            .setIamConfiguration(iamConfiguration)
            .setAcl(null)
            .setDefaultAcl(null)
            .build(),
        BucketTargetOption.metagenerationMatch());

    System.out.println("Uniform bucket-level access was enabled for " + bucketName);
  }
}

以下示例在存储桶上禁用统一存储桶级访问权限:


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.Storage.BucketTargetOption;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

public class DisableUniformBucketLevelAccess {
  public static void disableUniformBucketLevelAccess(String projectId, String bucketName)
      throws StorageException {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    // first look up the bucket, so we will have its metageneration
    Bucket bucket = storage.get(bucketName);

    BucketInfo.IamConfiguration iamConfiguration =
        BucketInfo.IamConfiguration.newBuilder()
            .setIsUniformBucketLevelAccessEnabled(false)
            .build();

    storage.update(
        bucket.toBuilder().setIamConfiguration(iamConfiguration).build(),
        BucketTargetOption.metagenerationMatch());

    System.out.println("Uniform bucket-level access was disabled for " + bucketName);
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

以下示例在存储桶上启用统一存储桶级访问权限:

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

以下示例在存储桶上禁用统一存储桶级访问权限:

/**
 * 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
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

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

以下示例在存储桶上启用统一存储桶级访问权限:

use Google\Cloud\Storage\StorageClient;

/**
 * Enable uniform bucket-level access.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function enable_uniform_bucket_level_access(string $bucketName): void
{
    $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);
}

以下示例在存储桶上禁用统一存储桶级访问权限:

use Google\Cloud\Storage\StorageClient;

/**
 * Enable uniform bucket-level access.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function disable_uniform_bucket_level_access(string $bucketName): void
{
    $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

如需了解详情,请参阅 Cloud Storage Python API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

以下示例在存储桶上启用统一存储桶级访问权限:

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(
        f"Uniform bucket-level access was enabled for {bucket.name}."
    )

以下示例在存储桶上禁用统一存储桶级访问权限:

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(
        f"Uniform bucket-level access was disabled for {bucket.name}."
    )

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

以下示例在存储桶上启用统一存储桶级访问权限:

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

  require "google/cloud/storage"

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

  bucket.uniform_bucket_level_access = true

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

以下示例在存储桶上禁用统一存储桶级访问权限:

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

  require "google/cloud/storage"

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

  bucket.uniform_bucket_level_access = false

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

REST API

JSON API

  1. 安装并初始化 gcloud CLI,以便为 Authorization 标头生成访问令牌。

    或者,您可以创建访问令牌(使用 OAuth 2.0 Playground),并将其包含在 Authorization 标头中。

  2. 创建一个包含以下信息的 JSON 文件:

    {
      "iamConfiguration": {
          "uniformBucketLevelAccess": {
            "enabled": STATE
          }
      }
    }

    其中 STATEtruefalse

  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API:

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

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的文件的路径。
    • BUCKET_NAME 是相关存储桶的名称,例如 my-bucket

XML API

XML API 不能用于处理统一存储桶级访问权限。请改用其他 Cloud Storage 工具之一,例如 gcloud CLI。

查看统一存储桶级访问权限状态

控制台

  1. 在 Google Cloud 控制台中,进入 Cloud Storage 存储桶页面。

    进入“存储桶”

  2. 点击您要查看其状态的存储桶的名称。

  3. 点击配置标签页。

    您可以在访问权限控制字段中找到存储桶的统一存储桶级访问权限状态。

如需了解如何在 Google Cloud 控制台中获取失败的 Cloud Storage 操作的详细错误信息,请参阅问题排查

命令行

使用带有 --format 标志的 gcloud storage buckets describe 命令:

gcloud storage buckets describe gs://BUCKET_NAME --format="default(uniform_bucket_level_access)"

其中 BUCKET_NAME 是相关存储桶的名称,例如 my-bucket

如果成功,响应将如下所示:

uniform_bucket_level_access: true

客户端库

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name);
  if (!bucket_metadata) throw std::move(bucket_metadata).status();

  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#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Cloud.Storage.V1;
using System;
using static Google.Apis.Storage.v1.Data.Bucket.IamConfigurationData;

public class GetUniformBucketLevelAccessSample
{
    public UniformBucketLevelAccessData GetUniformBucketLevelAccess(
        string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        var uniformBucketLevelAccess = bucket.IamConfiguration.UniformBucketLevelAccess;

        bool uniformBucketLevelAccessEnabled = uniformBucketLevelAccess.Enabled ?? 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}.");
        }
        return uniformBucketLevelAccess;
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// getUniformBucketLevelAccess gets uniform bucket-level access.
func getUniformBucketLevelAccess(w io.Writer, bucketName string) (*storage.BucketAttrs, error) {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return nil, fmt.Errorf("Bucket(%q).Attrs: %w", bucketName, err)
	}
	uniformBucketLevelAccess := attrs.UniformBucketLevelAccess
	if uniformBucketLevelAccess.Enabled {
		fmt.Fprintf(w, "Uniform bucket-level access is enabled for %q.\n", attrs.Name)
		fmt.Fprintf(w, "Bucket will be locked on %q.\n", uniformBucketLevelAccess.LockedTime)
	} else {
		fmt.Fprintf(w, "Uniform bucket-level access is not enabled for %q.\n", attrs.Name)
	}
	return attrs, nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
import java.util.Date;

public class GetUniformBucketLevelAccess {
  public static void getUniformBucketLevelAccess(String projectId, String bucketName)
      throws StorageException {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket =
        storage.get(
            bucketName, Storage.BucketGetOption.fields(Storage.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

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * 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
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

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Storage\StorageClient;

/**
 * Enable uniform bucket-level access.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function get_uniform_bucket_level_access(string $bucketName): void
{
    $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

如需了解详情,请参阅 Cloud Storage Python API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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(
            f"Uniform bucket-level access is enabled for {bucket.name}."
        )
        print(
            "Bucket will be locked on {}.".format(
                iam_configuration.uniform_bucket_level_locked_time
            )
        )
    else:
        print(
            f"Uniform bucket-level access is disabled for {bucket.name}."
        )

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  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
end

REST API

JSON API

  1. 安装并初始化 gcloud CLI,以便为 Authorization 标头生成访问令牌。

    或者,您可以创建访问令牌(使用 OAuth 2.0 Playground),并将其包含在 Authorization 标头中。

  2. 使用 cURL,通过包含所需 fieldsGET Bucket 请求调用 JSON API:

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

    其中 BUCKET_NAME 是相关存储桶的名称,例如 my-bucket

    如果存储桶启用了统一存储桶级访问权限,则响应将类似于如下所示:

    {
      "iamConfiguration": {
          "uniformBucketLevelAccess": {
            "enabled": true,
            "lockedTime": "LOCK_DATE"
          }
        }
      }

XML API

XML API 不能用于处理统一存储桶级访问权限。请改用其他 Cloud Storage 工具之一,例如 gcloud CLI。

后续步骤