使用“仅限存储分区政策”功能

本页面显示如何在 Cloud Storage 存储分区上启用和停用“仅限存储分区政策”功能以及如何检查此功能的状态。如需详细了解此功能,请参阅仅限存储分区政策

前提条件

在 Cloud Storage 中使用此功能之前,您应该:

  1. 具备足够的权限来查看和更新 Cloud Storage 中的存储分区:

    • 如果您拥有包含该存储分区的项目,您很可能具备所需的权限。

    • 您应对相关存储分区具有 storage.buckets.updatestorage.buckets.get IAM 权限。如需了解如何获取具有这些权限的角色(例如 roles/storage.admin),请参阅使用 IAM 权限

检查 ACL 使用情况

启用“仅限存储分区政策”功能之前,请使用 Stackdriver 确保存储分区没有将 ACL 用于任何工作流。如需了解详情,请参阅检查对象 ACL 的使用情况

控制台

  1. 打开 Stackdriver Metrics Explorer。

    转到 Metrics Explorer

    如果您以前从未用过 Stackdriver,请点击创建工作区按钮,然后为包含存储分区的项目创建一个工作区。

  2. 查找资源类型和指标 (Find resource type and metric) 文本框中,输入 storage.googleapis.com/authz/acl_operations_count

    关联的图表会显示您正在使用的 ACL 操作。如果该指标不存在,则说明您的项目最近没有使用 ACL。

  3. (可选)如需按存储分区和 ACL 操作对数据进行分组,请为分组依据选择 acl_operation,并为聚合器 (Aggregator) 选择求和 (sum)。

如需查看可用指标的完整列表,请参阅 Stackdriver 指标文档。如需详细了解如何使用 Metrics Explorer,请参阅指标、时间序列和资源

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  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 [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json'

其中:

  • [PROJECT_ID] 是您要查看其 ACL 使用情况的项目 ID 或编号,例如 my-project
  • [END_TIME] 是您要查看其 ACL 使用情况的时间范围的结束时间,例如 2014-11-02T15:01:23.045123456Z
  • [START_TIME] 是您要查看其 ACL 使用情况的时间范围的开始时间,例如 2014-10-02T15:01:23.045123456Z
  • [YOUR_ACCESS_TOKEN] 是您在第 1 步中生成的访问令牌。

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

启用“仅限存储分区政策”功能

如需为您的存储分区启用“仅限存储分区政策”功能,请执行以下操作:

控制台

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,点击所需存储分区的名称。

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

  4. 选择仅限存储分区政策,简化访问权限控制文本框中,点击启用。

  5. 在出现的确认对话框中,点击确认

gsutil

bucketpolicyonly set 命令中使用 on 选项,注意要将方括号中的值替换为适当的值:

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

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

Enabling Bucket Policy Only for gs://test-bucket/...

代码示例

C++

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

namespace gcs = google::cloud::storage;
using google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.bucket_policy_only = gcs::BucketPolicyOnly{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 Bucket Policy Only on bucket "
            << updated_metadata->name() << "\n";
}

C#

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

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

            Console.WriteLine($"Bucket Policy Only was enabled for {bucketName}.");
        }

Go

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

bucket := c.Bucket(bucketName)
enableBucketPolicyOnly := storage.BucketAttrsToUpdate{
	BucketPolicyOnly: &storage.BucketPolicyOnly{
		Enabled: true,
	},
}
if _, err := bucket.Update(ctx, enableBucketPolicyOnly); err != nil {
	return err
}

Java

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

// 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().setIsBucketPolicyOnlyEnabled(true).build();
Bucket bucket =
    storage.update(
        BucketInfo.newBuilder(bucketName).setIamConfiguration(iamConfiguration).build());

System.out.println("Bucket Policy Only was enabled for " + bucketName);

Node.js

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

// 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 Bucket Policy Only for the bucket
await storage.bucket(bucketName).setMetadata({
  iamConfiguration: {
    bucketPolicyOnly: {
      enabled: true,
    },
  },
});

console.log(`Bucket Policy Only was enabled for ${bucketName}.`);

PHP

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

use Google\Cloud\Storage\StorageClient;

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

Python

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

# bucket_name = "my-bucket"

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

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

print('Bucket Policy Only was enabled for {}.'.format(bucket.name))

Ruby

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

# 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.policy_only = true

puts "Bucket Policy Only was enabled for #{bucket_name}."

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件,注意要将方括号中的值替换为适当的值:

    {
      "iamConfiguration": {
          "bucketPolicyOnly": {
            "enabled": true
          }
      }
    }
  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API,注意要将方括号中的值替换为适当的值:

    curl -X PATCH --data-binary @[JSON_FILE_NAME].json \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    -H "Content-Type: application/json" \
    "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=iamConfiguration"

XML API

您不能使用 XML API 来处理“仅限存储分区政策”功能。请使用其他 Cloud Storage 工具,例如 gsutil。

查看“仅限存储分区政策”功能的状态

控制台

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在“列”下拉菜单中,请务必勾选访问权限控制模型

  3. 在存储分区列表中,可在访问权限控制模型列中找到每个存储分区的“仅限存储分区政策”功能的状态。

gsutil

使用 bucketpolicyonly get 命令,注意要将方括号中的值替换为适当的值:

gsutil bucketpolicyonly get gs://[BUCKET_NAME]/

如果启用了“仅限存储分区政策”功能,则响应将如下所示:

Bucket Policy Only setting for gs://[BUCKET_NAME]/:
    Enabled: True
    LockedTime: [LOCK_DATE] 

代码示例

C++

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

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().bucket_policy_only.has_value()) {
    gcs::BucketPolicyOnly bucket_policy_only =
        *bucket_metadata->iam_configuration().bucket_policy_only;

    std::cout << "Bucket Policy Only is enabled for "
              << bucket_metadata->name() << "\n";
    std::cout << "Bucket will be locked on " << bucket_policy_only << "\n";
  } else {
    std::cout << "Bucket Policy Only is not enabled for "
              << bucket_metadata->name() << "\n";
  }
}

C#

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

        private void GetBucketPolicyOnly(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            var bucketPolicyOnly = bucket.IamConfiguration.BucketPolicyOnly;

            bool? enabledOrNull = bucketPolicyOnly?.Enabled;
            bool bucketPolicyEnabled =
                enabledOrNull.HasValue ? enabledOrNull.Value : false;
            if (bucketPolicyEnabled)
            {
                Console.WriteLine($"Bucket Policy Only is enabled for {bucketName}.");
                Console.WriteLine(
                    $"Bucket Policy Only will be locked on {bucketPolicyOnly.LockedTime}.");
            }
            else
            {
                Console.WriteLine($"Bucket Policy Only is not enabled for {bucketName}.");
            }
        }

Go

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

attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return nil, err
}
bucketPolicyOnly := attrs.BucketPolicyOnly
if bucketPolicyOnly.Enabled {
	log.Printf("Bucket Policy Only is enabled for %q.\n",
		attrs.Name)
	log.Printf("Bucket will be locked on %q.\n",
		bucketPolicyOnly.LockedTime)
} else {
	log.Printf("Bucket Policy Only is not enabled for %q.\n",
		attrs.Name)
}

Java

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

// 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.isBucketPolicyOnlyEnabled();
Date lockedTime = new Date(iamConfiguration.getBucketPolicyOnlyLockedTime());

if (enabled != null && enabled) {
  System.out.println("Bucket Policy Only is enabled for " + bucketName);
  System.out.println("Bucket will be locked on " + lockedTime);
} else {
  System.out.println("Bucket Policy Only is disabled for " + bucketName);
}

Node.js

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

// 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 BucketPolicyOnly is enabled.
const [metadata] = await storage.bucket(bucketName).getMetadata();

if (metadata.iamConfiguration) {
  const bucketPolicyOnly = metadata.iamConfiguration.bucketPolicyOnly;
  console.log(`Bucket Policy Only is enabled for ${bucketName}.`);
  console.log(`Bucket will be locked on ${bucketPolicyOnly.lockedTime}.`);
} else {
  console.log(`Bucket Policy Only is not enabled for ${bucketName}.`);
}

PHP

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

use Google\Cloud\Storage\StorageClient;

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

Python

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

# bucket_name = "my-bucket"

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

if iam_configuration.bucket_policy_only_enabled:
    print('Bucket Policy Only is enabled for {}.'.format(bucket.name))
    print('Bucket will be locked on {}.'.format(
        iam_configuration.bucket_policy_only_locked_time))
else:
    print('Bucket Policy Only is disabled for {}.'.format(bucket.name))

Ruby

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

# 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.policy_only?
  puts "Bucket Policy Only is enabled for #{bucket_name}."
  puts "Bucket will be locked on #{bucket.policy_only_locked_at}."
else
  puts "Bucket Policy Only is disabled for #{bucket_name}."
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过包含所需 fieldsGET Bucket 请求调用 JSON API,注意要将方括号中的值替换为适当的值:

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

    如果存储分区启用了“仅限存储分区政策”功能,则响应如下所示:

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

XML API

您不能使用 XML API 来处理“仅限存储分区政策”功能。请使用其他 Cloud Storage 工具,例如 gsutil。

停用“仅限存储分区政策”功能

要为您的存储分区停用“仅限存储分区政策”功能,请执行以下操作:

控制台

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,点击所需存储分区的名称。

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

  4. 对象级权限已停用文本框中,点击启用。

  5. 在出现的确认对话框中,点击确认

gsutil

bucketpolicyonly set 命令中使用 off 选项,注意要将方括号中的值替换为适当的值:

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

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

Disabling Bucket Policy Only for gs://test-bucket/...

代码示例

C++

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

namespace gcs = google::cloud::storage;
using google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.bucket_policy_only = gcs::BucketPolicyOnly{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 Bucket Policy Only on bucket "
            << updated_metadata->name() << "\n";
}

C#

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

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

            Console.WriteLine($"Bucket Policy Only was disabled for {bucketName}.");
        }

Go

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

bucket := c.Bucket(bucketName)
disableBucketPolicyOnly := storage.BucketAttrsToUpdate{
	BucketPolicyOnly: &storage.BucketPolicyOnly{
		Enabled: false,
	},
}
if _, err := bucket.Update(ctx, disableBucketPolicyOnly); err != nil {
	return err
}

Java

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

// 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().setIsBucketPolicyOnlyEnabled(false).build();
Bucket bucket =
    storage.update(
        BucketInfo.newBuilder(bucketName).setIamConfiguration(iamConfiguration).build());

System.out.println("Bucket Policy Only was disabled for " + bucketName);

Node.js

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

// 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 Bucket Policy Only for the bucket
await storage.bucket(bucketName).setMetadata({
  iamConfiguration: {
    bucketPolicyOnly: {
      enabled: false,
    },
  },
});

console.log(`Bucket Policy Only was disabled for ${bucketName}.`);

PHP

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

use Google\Cloud\Storage\StorageClient;

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

Python

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

# bucket_name = "my-bucket"

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

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

print('Bucket Policy Only was disabled for {}.'.format(bucket.name))

Ruby

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

# 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.policy_only = false

puts "Bucket Policy Only was disabled for #{bucket_name}."

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件,注意要将方括号中的值替换为适当的值:

    {
      "iamConfiguration": {
          "bucketPolicyOnly": {
            "enabled": false
          }
      }
    }
  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API,注意要将方括号中的值替换为适当的值:

    curl -X PATCH --data-binary @[JSON_FILE_NAME].json \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    -H "Content-Type: application/json" \
    "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=iamConfiguration"

XML API

您不能使用 XML API 来处理“仅限存储分区政策”功能。请使用其他 Cloud Storage 工具,例如 gsutil。

后续步骤

此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Cloud Storage
需要帮助?请访问我们的支持页面