使用保留政策及值區鎖定功能

本頁說明如何使用值區鎖定功能,包括使用保留政策和鎖定值區。如要進一步瞭解此功能,請參閱保留政策及值區鎖定功能相關頁面。

必備條件

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

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

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

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

    • 如果您使用 ACL,則應具備相關值區的「擁有者」權限。相關操作說明,請參閱設定 ACL 一節。

  2. 針對值區,檢查物件版本管理功能是否停用

設定值區的保留政策

如要設定值區的保留政策:

主控台

  1. 在 Google Cloud Platform 主控台中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中,找出您要新增保留政策的值區,然後點選該值區名稱。

  3. 選取靠近頁面上方的 [Bucket Lock] (值區鎖定功能) 分頁標籤。

  4. 在「Retention policy」(保留政策) 項目中,按一下 [Add policy] (新增政策) 連結。

    即會顯示「Set a retention policy」(設定保留政策) 對話方塊。

  5. 在下拉式選單中,選取保留期限的時間單位。

    要瞭解主控台如何轉換不同的時間單位,請參閱保留期限一節。

  6. 在值方塊中,輸入保留期限的時間長度。

  7. 按一下 [Save Policy] (儲存政策)。

gsutil

使用 gsutil retention set 指令,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

gsutil retention set [TIME_DURATION] gs://[BUCKET_NAME]

要瞭解 gsutil 如何轉換不同的時間單位,請參閱保留期限一節。

如果成功,回應如下所示:

Setting retention policy on gs://[BUCKET_NAME]/...

程式碼範例

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

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

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

  StatusOr<gcs::BucketMetadata> patched_metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetRetentionPolicy(period),
      gcs::IfMetagenerationMatch(original->metageneration()));

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

  if (!patched_metadata->has_retention_policy()) {
    std::cout << "The bucket " << patched_metadata->name()
              << " does not have a retention policy set.\n";
    return;
  }

  std::cout << "The bucket " << patched_metadata->name()
            << " retention policy is set to "
            << patched_metadata->retention_policy() << "\n";
}

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

        private void SetBucketRetentionPolicy(string bucketName,
            long retentionPeriod)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            bucket.RetentionPolicy = new Bucket.RetentionPolicyData();
            bucket.RetentionPolicy.RetentionPeriod = retentionPeriod;
            bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
            {
                IfMetagenerationMatch = bucket.Metageneration
            });

            Console.WriteLine($"Retention policy for {bucketName} was set to {retentionPeriod}");
        }

Go

詳情請參閱 Cloud Storage Go API 參考說明文件

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	RetentionPolicy: &storage.RetentionPolicy{
		RetentionPeriod: retentionPeriod,
	},
}
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); 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";

// The retention period for objects in bucket
// Long retentionPeriod = 3600L; // 1 hour in seconds

Bucket bucketWithRetentionPolicy =
    storage.update(
        BucketInfo.newBuilder(bucketName).setRetentionPeriod(retentionPeriod).build());

System.out.println(
    "Retention period for "
        + bucketName
        + " is now "
        + bucketWithRetentionPolicy.getRetentionPeriod());

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();

const [metadata] = await storage
  .bucket(bucketName)
  .setRetentionPeriod(retentionPeriod);
console.log(
  `Bucket ${bucketName} retention period set for ${
    metadata.retentionPolicy.retentionPeriod
  } seconds.`
);

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

use Google\Cloud\Storage\StorageClient;

/**
 * Sets a bucket's retention policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $retentionPeriod the number of seconds for your retention period.
 */
function set_retention_policy($bucketName, $retentionPeriod)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'retentionPolicy' => [
            'retentionPeriod' => $retentionPeriod
        ]]);
    printf('Bucket %s retention period set for %s seconds' . PHP_EOL, $bucketName,
        $retentionPeriod);
}

Python

詳情請參閱 Cloud Storage Python API 參考說明文件

# bucket_name = "my-bucket"
# retention_period = 10

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

bucket.retention_period = retention_period
bucket.patch()

print('Bucket {} retention period set for {} seconds'.format(
    bucket.name,
    bucket.retention_period))

Ruby

詳情請參閱 Cloud Storage Ruby API 參考說明文件

# project_id       = "Your Google Cloud project ID"
# bucket_name      = "Name of your Google Cloud Storage bucket"
# retention_period = "Object retention period defined in seconds"

require "google/cloud/storage"

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

bucket.retention_period = retention_period

puts "Retention period for #{bucket_name} is now #{bucket.retention_period} seconds."

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用您自己的 OAuth 憑證。
  2. 建立一個包含下列資訊的 .json 檔案,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

    {
      "retentionPolicy": {
        "retentionPeriod": "[TIME_IN_SECONDS]"
      }
    }
  3. 透過 PATCH Bucket 要求使用 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=retentionPolicy"

XML API

XML API 不能用來設定現有值區的保留政策,只能用來在新值區中納入保留政策

移除值區的保留政策

如要移除值區的保留政策:

主控台

  1. 在 Google Cloud Platform 主控台中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中,找出您要移除保留政策的值區,然後點選該值區的名稱。

  3. 選取靠近頁面上方的 [Bucket Lock] (值區鎖定功能) 分頁標籤。

  4. 在「Retention policy」(保留政策) 項目中,按一下「垃圾桶圖示」

    即會顯示「Delete retention policy?」(要刪除保留政策嗎?) 對話方塊。

  5. 按一下 [Delete] (刪除)

gsutil

使用 gsutil retention clear 指令,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

gsutil retention clear gs://[BUCKET_NAME]

如果成功,回應如下所示:

Clearing retention policy on gs://[BUCKET_NAME]/...

程式碼範例

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

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

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

  StatusOr<gcs::BucketMetadata> patched_metadata = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().ResetRetentionPolicy(),
      gcs::IfMetagenerationMatch(original->metageneration()));

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

  if (!patched_metadata->has_retention_policy()) {
    std::cout << "The bucket " << patched_metadata->name()
              << " does not have a retention policy set.\n";
    return;
  }

  std::cout << "The bucket " << patched_metadata->name()
            << " retention policy is set to "
            << patched_metadata->retention_policy()
            << ". This is unexpected, maybe a concurrent change by another"
            << " application?\n";
}

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

        private void RemoveBucketRetentionPolicy(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            if (bucket.RetentionPolicy != null)
            {
                bool? isLockedOrNull = bucket?.RetentionPolicy.IsLocked;
                bool isLocked =
                    isLockedOrNull.HasValue ? isLockedOrNull.Value : false;
                if (isLocked)
                {
                    throw new Exception("Retention Policy is locked.");
                }

                bucket.RetentionPolicy.RetentionPeriod = null;
                bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
                {
                    IfMetagenerationMatch = bucket.Metageneration
                });

                Console.WriteLine($"Retention period for {bucketName} has been removed.");
            }
        }

Go

詳情請參閱 Cloud Storage Go API 參考說明文件

bucket := c.Bucket(bucketName)

attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}
if attrs.RetentionPolicy.IsLocked {
	return errors.New("retention policy is locked")
}

bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	RetentionPolicy: &storage.RetentionPolicy{},
}
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); 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";

Bucket bucket = storage.get(bucketName, BucketGetOption.fields(BucketField.RETENTION_POLICY));
if (bucket.retentionPolicyIsLocked() != null && bucket.retentionPolicyIsLocked()) {
  throw new IllegalArgumentException(
      "Unable to remove retention period as retention policy is locked.");
}

Bucket bucketWithoutRetentionPolicy =
    bucket.toBuilder().setRetentionPeriod(null).build().update();

System.out.println("Retention period for " + bucketName + " has been removed");

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();
const [metadata] = await storage.bucket(bucketName).getMetadata();
if (
  metadata.hasOwnProperty('retentionPolicy') &&
  metadata.retentionPolicy.hasOwnProperty('isLocked')
) {
  console.log(
    'Unable to remove retention period as retention policy is locked.'
  );
  return null;
} else {
  const results = await storage.bucket(bucketName).removeRetentionPeriod();
  console.log(`Removed bucket ${bucketName} retention policy.`);
  return results;
}

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

use Google\Cloud\Storage\StorageClient;

/**
 * Removes a bucket's retention policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function remove_retention_policy($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->reload();

    if (array_key_exists('isLocked', $bucket->info()['retentionPolicy']) &&
        $bucket->info()['retentionPolicy']['isLocked']) {
        printf('Unable to remove retention period as retention policy is locked.' . PHP_EOL);
        return;
    }

    $bucket->update([
        'retentionPolicy' => []
    ]);
    printf('Removed bucket %s retention policy' . PHP_EOL, $bucketName);
}

Python

詳情請參閱 Cloud Storage Python API 參考說明文件

# bucket_name = "my-bucket"

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

if bucket.retention_policy_locked:
    print(
        'Unable to remove retention period as retention policy is locked.')
    return

bucket.retention_period = None
bucket.patch()

print('Removed bucket {} retention policy'.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.retention_policy_locked?
  bucket.retention_period = nil
  puts "Retention policy for #{bucket_name} has been removed."
else
  puts "Policy is locked and retention policy can't be removed."
end

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用您自己的 OAuth 憑證。
  2. 建立包含下列資訊的 .json 檔案:

    {
      "retentionPolicy": {
        "retentionPeriod": null
      }
    }
  3. 透過 PATCH Bucket 要求使用 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=retentionPolicy"

XML API

XML API 無法用來移除值區的保留政策。請改用 gsutil 等其他 Cloud Storage 工具。

鎖定值區

如要鎖定值區並永久限制值區保留政策的編輯動作:

主控台

  1. 在 Google Cloud Platform 主控台中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中,找出您要鎖定保留政策的值區,然後點選該值區的名稱。

  3. 選取靠近頁面上方的 [Bucket Lock] (值區鎖定功能) 分頁標籤。

  4. 在「Locked」(已鎖定) 項目中,按一下「鎖頭圖示」

    即會顯示「Lock retention policy for this bucket?」(要為此值區鎖定保留政策嗎?) 對話方塊。

  5. 讀取「Permanent」(永久) 通知。

  6. 在「Bucket name」(值區名稱) 文字方塊中,輸入值區的名稱。

  7. 按一下 [Lock policy] (鎖定政策)。

gsutil

  1. 使用 gsutil retention lock 指令,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

    gsutil retention lock gs://[BUCKET_NAME]
  2. 系統顯示是否繼續執行的提示時,輸入 y

如果成功,回應如下所示:

Locking retention policy on gs://[BUCKET_NAME]/...

程式碼範例

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

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

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

  StatusOr<gcs::BucketMetadata> updated_metadata =
      client.LockBucketRetentionPolicy(bucket_name,
                                       original->metageneration());

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

  if (!updated_metadata->has_retention_policy()) {
    std::cerr << "The bucket " << updated_metadata->name()
              << " does not have a retention policy, even though the"
              << " operation to set it was successful.\n"
              << "This is unexpected, and may indicate that another"
              << " application has modified the bucket concurrently.\n";
    return;
  }

  std::cout << "Retention policy successfully locked for bucket "
            << updated_metadata->name() << "\nNew retention policy is: "
            << updated_metadata->retention_policy()
            << "\nFull metadata: " << *updated_metadata << "\n";
}

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

private void LockBucketRetentionPolicy(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName);
    storage.LockBucketRetentionPolicy(bucketName,
        bucket.Metageneration.Value);
    bucket = storage.GetBucket(bucketName);
    Console.WriteLine($"Retention policy for {bucketName} is now locked");
    Console.WriteLine($"Retention policy effective as of {bucket.RetentionPolicy.EffectiveTime}");
}

Go

詳情請參閱 Cloud Storage Go API 參考說明文件

bucket := c.Bucket(bucketName)
attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}

conditions := storage.BucketConditions{
	MetagenerationMatch: attrs.MetaGeneration,
}
if err := bucket.If(conditions).LockRetentionPolicy(ctx); err != nil {
	return err
}

lockedAttrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}
log.Printf("Retention policy for %v is now locked\n", bucketName)
log.Printf("Retention policy effective as of %v\n",
	lockedAttrs.RetentionPolicy.EffectiveTime)

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, Storage.BucketGetOption.fields(BucketField.METAGENERATION));
Bucket lockedBucket =
    bucket.lockRetentionPolicy(Storage.BucketTargetOption.metagenerationMatch());

System.out.println("Retention period for " + bucketName + " is now locked");
System.out.println(
    "Retention policy effective as of " + new Date(lockedBucket.getRetentionEffectiveTime()));

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();
// get_bucket gets the current metageneration value for the bucket,
// required by lock_retention_policy.
const [unlockedMetadata] = await storage.bucket(bucketName).getMetadata();
// Warning: Once a retention policy is locked it cannot be unlocked
// and retention period can only be increased.
const [lockedMetadata] = await storage
  .bucket(bucketName)
  .lock(unlockedMetadata.metageneration);
console.log(`Retention policy for ${bucketName} is now locked.`);
console.log(
  `Retention policy effective as of ${
    lockedMetadata.retentionPolicy.effectiveTime
  }`
);

return lockedMetadata;

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

use Google\Cloud\Storage\StorageClient;

/**
 * Locks a bucket's retention policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function lock_retention_policy($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->reload();
    $bucket->lockRetentionPolicy();
    printf('Bucket %s retention policy locked' . PHP_EOL, $bucketName);
}

Python

詳情請參閱 Cloud Storage Python API 參考說明文件

# bucket_name = "my-bucket"

storage_client = storage.Client()
# get_bucket gets the current metageneration value for the bucket,
# required by lock_retention_policy.
bucket = storage_client.get_bucket(bucket_name)

# Warning: Once a retention policy is locked it cannot be unlocked
# and retention period can only be increased.
bucket.lock_retention_policy()

print('Retention policy for {} is now locked'.format(bucket_name))
print('Retention policy effective as of {}'.format(
    bucket.retention_policy_effective_time))

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

# Warning: Once a retention policy is locked it cannot be unlocked
# and retention period can only be increased.
# Uses Bucket#metageneration as a precondition.
bucket.lock_retention_policy!

puts "Retention policy for #{bucket_name} is now locked."
puts "Retention policy effective as of #{bucket.retention_effective_at}."

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用您自己的 OAuth 憑證。
  2. 透過 POST Bucket 要求使用 cURL 呼叫 JSON API,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

    curl -X POST \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/lockRetentionPolicy?ifMetagenerationMatch=[BUCKET_METAGENERATION_NUMBER]"

XML API

XML API 無法用來鎖定值區,請改用 gsutil 等其他 Cloud Storage 工具。

查看值區的保留政策和鎖定狀態

如果查看值區設定的保留政策 (如果有),以及該保留政策是否鎖定:

主控台

  1. 在 Google Cloud Platform 主控台中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在「Columns」(資料欄) 下拉式選單中,確認已勾選 [Retention policy] (保留政策)。

  3. 在值區清單中,每個值區的保留期限會顯示在「Retention policy」(保留政策) 資料欄中。如果保留政策已鎖定,系統會直接在保留期限的左側顯示鎖定圖片。

gsutil

使用 gsutil retention get 指令,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

gsutil retention get gs://[BUCKET_NAME]

如果成功,回應如下所示:

gs://[BUCKET_NAME]/ has no retention policy.

或:

gs://retention-test/:
    Retention policy [LOCK_STATUS]:
    Duration: [TIME_LENGTH]
    Effective Time: [SET_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_retention_policy()) {
    std::cout << "The bucket " << bucket_metadata->name()
              << " does not have a retention policy set.\n";
    return;
  }

  std::cout << "The bucket " << bucket_metadata->name()
            << " retention policy is set to "
            << bucket_metadata->retention_policy() << "\n";
}

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

        private void GetBucketRetentionPolicy(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);

            if (bucket.RetentionPolicy != null)
            {
                Console.WriteLine("Retention policy:");
                Console.WriteLine($"period: {bucket.RetentionPolicy.RetentionPeriod}");
                Console.WriteLine($"effective time: {bucket.RetentionPolicy.EffectiveTime}");
                bool? isLockedOrNull = bucket?.RetentionPolicy.IsLocked;
                bool isLocked =
                    isLockedOrNull.HasValue ? isLockedOrNull.Value : false;
                Console.WriteLine("policy locked: {0}", isLocked);
            }
        }

Go

詳情請參閱 Cloud Storage Go API 參考說明文件

attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return nil, err
}
if attrs.RetentionPolicy != nil {
	log.Print("Retention Policy\n")
	log.Printf("period: %v\n", attrs.RetentionPolicy.RetentionPeriod)
	log.Printf("effective time: %v\n", attrs.RetentionPolicy.EffectiveTime)
	log.Printf("policy locked: %v\n", attrs.RetentionPolicy.IsLocked)
}

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.RETENTION_POLICY));

System.out.println("Retention Policy for " + bucketName);
System.out.println("Retention Period: " + bucket.getRetentionPeriod());
if (bucket.retentionPolicyIsLocked() != null && bucket.retentionPolicyIsLocked()) {
  System.out.println("Retention Policy is locked");
}
if (bucket.getRetentionEffectiveTime() != null) {
  System.out.println("Effective Time: " + new Date(bucket.getRetentionEffectiveTime()));
}

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();
const [metadata] = await storage.bucket(bucketName).getMetadata();
if (metadata.hasOwnProperty('retentionPolicy')) {
  const retentionPolicy = metadata.retentionPolicy;
  console.log('A retention policy exists!');
  console.log(`Period: ${retentionPolicy.retentionPeriod}`);
  console.log(`Effective time: ${retentionPolicy.effectiveTime}`);
  if (retentionPolicy.hasOwnProperty('isLocked')) {
    console.log('Policy is locked');
  } else {
    console.log('Policy is unlocked');
  }
}

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

use Google\Cloud\Storage\StorageClient;

/**
 * Gets a bucket's retention policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function get_retention_policy($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->reload();

    printf('Retention Policy for ' . $bucketName . PHP_EOL);
    printf('Retention Period: ' . $bucket->info()['retentionPolicy']['retentionPeriod'] . PHP_EOL);
    if (array_key_exists('isLocked', $bucket->info()['retentionPolicy']) &&
        $bucket->info()['retentionPolicy']['isLocked']) {
        printf('Retention Policy is locked' . PHP_EOL);
    }
    if ($bucket->info()['retentionPolicy']['effectiveTime']) {
        printf('Effective Time: ' . $bucket->info()['retentionPolicy']['effectiveTime'] . PHP_EOL);
    }
}

Python

詳情請參閱 Cloud Storage Python API 參考說明文件

# bucket_name = "my-bucket"

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

print('Retention Policy for {}'.format(bucket_name))
print('Retention Period: {}'.format(bucket.retention_period))
if bucket.retention_policy_locked:
    print('Retention Policy is locked')

if bucket.retention_policy_effective_time:
    print('Effective Time: {}'
          .format(bucket.retention_policy_effective_time))

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

puts "Retention policy:"
puts "period: #{bucket.retention_period}"
puts "effective time: #{bucket.retention_effective_at}"
puts "policy locked: #{bucket.retention_policy_locked?}"

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用您自己的 OAuth 憑證。
  2. 透過內含所需 fieldsGET Bucket 要求,使用 cURL 呼叫 JSON API,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

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

    如果值區已設定保留政策,回應會如下列範例所示:

    {
      "retentionPolicy": {
          "retentionPeriod": "[TIME_IN_SECONDS]",
          "effectiveTime": "[DATETIME]",
          "isLocked": "[BOOLEAN]"
       },
    }

XML API

XML API 不能用來查看值區的保留政策,請改用 gsutil 等其他 Cloud Storage 工具。

後續步驟

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

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

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