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

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

前提条件

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

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

    • 如果您是该存储分区所属项目的所有者,则您很可能具备必要的权限。

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

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

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

Console

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

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

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

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

gsutil

bucketpolicyonly set 命令中使用 on 选项,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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 文件,并将 [VALUES_IN_BRACKETS] 替换为适当的值:

    {
      "iamConfiguration": {
          "bucketPolicyOnly": {
            "enabled": true
          }
      }
    }
  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

    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。

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

Console

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

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

gsutil

使用 bucketpolicyonly get 命令,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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.hasOwnProperty('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,将 [VALUES_IN_BRACKETS] 替换为适当的值:

    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。

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

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

Console

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

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

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

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

gsutil

bucketpolicyonly set 命令中使用 off 选项,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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 文件,并将 [VALUES_IN_BRACKETS] 替换为适当的值:

    {
      "iamConfiguration": {
          "bucketPolicyOnly": {
            "enabled": false
          }
      }
    }
  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

    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
需要帮助?请访问我们的支持页面