使用「僅值區政策」

本頁面說明如何在 Cloud Storage 中,對值區執行「僅值區政策」的啟用、停用與狀態檢查。如要進一步瞭解這項功能,請參閱僅值區政策

必備條件

在 Cloud Storage 中使用這項功能之前,您應先具備以下條件:

  1. 具有足夠的權限可以查看和更新 Cloud Storage 中的值區:

    • 如果您擁有包含值區的專案,代表您非常可能已具備必要的權限。

    • 您應擁有相關值區上的 storage.buckets.updatestorage.buckets.get IAM 權限。請參閱使用 IAM 權限一文中的操作說明,瞭解如何取得具有這些權限的角色 (例如 roles/storage.admin)。

啟用「僅值區政策」

若要在您的值區上啟用「僅值區政策」:

主控台

  1. 在 Google Cloud Platform 主控台中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中點選所需值區名稱。

  3. 選取靠近頁面上方的 [Permissions] (權限) 分頁標籤。

  4. 在「Simplify access control with Bucket Policy Only」(透過「僅值區政策」簡化存取權控管作業) 文字方塊中,按一下 [Enable] (啟用)

  5. 在隨即顯示的確認對話方塊中,按一下 [Confirm] (確認)

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. 透過 PATCH 值區要求以使用 cURL 來呼叫 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 無法使用「僅值區政策」,請改用 gsutil 等其他 Cloud Storage 工具。

檢視「僅值區政策」狀態

主控台

  1. 在 Google Cloud Platform 主控台中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在「Columns」(資料欄) 下拉式選單中,確認已勾選 [Access control model] (存取權控管模型)。

  3. 在值區清單中,每個值區的「僅值區政策」狀態會顯示在「Access control model」(存取權控管模型) 一欄。

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. 透過內含所需 fieldsGET 值區要求,使用 cURL 來呼叫 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 無法使用「僅值區政策」,請改用 gsutil 等其他 Cloud Storage 工具。

停用「僅值區政策」

若要在您的值區上停用「僅值區政策」:

主控台

  1. 在 Google Cloud Platform 主控台中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中點選所需值區名稱。

  3. 選取靠近頁面上方的 [Permissions] (權限) 分頁標籤。

  4. 在「Object-level permissions are disabled」(已停用物件層級權限) 文字方塊中,按一下 [Enable] (啟用)

  5. 在隨即顯示的確認對話方塊中,按一下 [Confirm] (確認)

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. 透過 PATCH 值區要求以使用 cURL 來呼叫 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 無法使用「僅值區政策」,請改用 gsutil 等其他 Cloud Storage 工具。

後續步驟

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Storage
需要協助嗎?請前往我們的支援網頁