使用物件版本管理功能

總覽 使用方式

本頁說明如何啟用、停用及檢查值區的物件版本管理功能狀態。如要瞭解如何列出、還原及刪除物件版本管理功能保留的物件,請參閱「使用版本化物件」。

必要的角色

如要取得設定及管理值區物件版本控管所需的權限,請要求管理員為您授予值區或值區所屬專案的儲存空間管理員 (roles/storage.admin) 身分與存取權管理角色。這個預先定義的角色具備設定及管理值區物件版本控管功能所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

  • storage.buckets.get
  • storage.buckets.update
  • storage.buckets.list
    • 如果您打算使用Google Cloud 控制台執行本頁的操作說明,才需要這項權限。

您或許還可透過自訂角色取得這些權限。

如要瞭解如何授予值區角色,請參閱「搭配值區使用 IAM」。如要瞭解如何授予專案角色,請參閱「管理專案存取權」。

設定值區的物件版本管理功能

控制台

  1. 在 Google Cloud 控制台,前往「Cloud Storage bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 在 bucket 清單中,點選要啟用或停用物件版本的 bucket 名稱。

  3. 選取頁面頂端的「保護」分頁標籤。

    「物件版本管理」部分會顯示目前狀態。

  4. 在「物件版本管理」部分,按一下目前的狀態即可變更。

    系統會隨即顯示「物件版本管理」對話方塊。

    1. 如要啟用物件版本管理功能並盡量減少儲存空間費用,請勾選「按照建議新增生命週期規則來管理版本費用」核取方塊。
  5. 按一下「確認」。

指令列

使用 gcloud storage buckets update 指令並加上適當的旗標:

gcloud storage buckets update gs://BUCKET_NAME FLAG

其中:

  • BUCKET_NAME 是相關值區的名稱。例如:my-bucket

  • FLAG--versioning (啟用物件版本管理) 或 --no-versioning (停用物件版本管理)。

如果成功,回應會類似以下範例:

Updating gs://my-bucket/...
  Completed 1  

用戶端程式庫

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> original =
      client.GetBucketMetadata(bucket_name);
  if (!original) throw std::move(original).status();

  StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetVersioning(
          gcs::BucketVersioning{true}),
      gcs::IfMetagenerationMatch(original->metageneration()));
  if (!patched) throw std::move(patched).status();

  if (patched->versioning().has_value()) {
    std::cout << "Object versioning for bucket " << bucket_name << " is "
              << (patched->versioning()->enabled ? "enabled" : "disabled")
              << "\n";
  } else {
    std::cout << "Object versioning for bucket " << bucket_name
              << " is disabled.\n";
  }
}

下例示範如何停用值區的物件版本管理功能:

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

  StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetVersioning(
          gcs::BucketVersioning{false}),
      gcs::IfMetagenerationMatch(original->metageneration()));
  if (!patched) throw std::move(patched).status();

  auto versioning =
      patched->versioning().value_or(gcs::BucketVersioning{false});
  std::cout << "Object versioning for bucket " << bucket_name << " is "
            << (versioning.enabled ? "enabled" : "disabled") << "\n";
}

C#

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會啟用值區的物件版本管理功能:


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

public class BucketEnableVersioningSample
{
	public Bucket BucketEnableVersioning(string bucketName = "your-bucket-name")
	{
		var storage = StorageClient.Create();
		var bucket = storage.GetBucket(bucketName);

		if (bucket.Versioning == null)
		{
			bucket.Versioning = new Bucket.VersioningData();
		}
		bucket.Versioning.Enabled = true;

		bucket = storage.UpdateBucket(bucket);
		Console.WriteLine($"Versioning is now enabled for bucket {bucketName}.");
		return bucket;
	}
}

下例示範如何停用值區的物件版本管理功能:


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

public class BucketDisableVersioningSample
{
	public Bucket BucketDisableVersioning(string bucketName = "your-bucket-name")
	{
		var storage = StorageClient.Create();
		var bucket = storage.GetBucket(bucketName);

		if (bucket.Versioning?.Enabled != true)
		{
			Console.WriteLine($"Versioning already disabled for bucket {bucketName}.");
		}
		else
		{
        	    bucket.Versioning.Enabled = false;

		    bucket = storage.UpdateBucket(bucket);
                    Console.WriteLine($"Versioning is now disabled for bucket {bucketName}.");
                }
		return bucket;
	}
}

Go

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會啟用值區的物件版本管理功能:

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

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

// enableVersioning enables object versioning on a bucket.
func enableVersioning(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)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		VersioningEnabled: true,
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Versioning was enabled for %v\n", bucketName)
	return nil
}

下例示範如何停用值區的物件版本管理功能:

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

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

// disableVersioning disables object versioning on a bucket.
func disableVersioning(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)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		VersioningEnabled: false,
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Versioning 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.Storage;
import com.google.cloud.storage.StorageOptions;

public class EnableBucketVersioning {
  public static void enableBucketVersioning(String projectId, String bucketName) {
    // 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);
    bucket.toBuilder().setVersioningEnabled(true).build().update();

    System.out.println("Versioning is now enabled for bucket " + bucketName);
  }
}

下例示範如何停用值區的物件版本管理功能:

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class DisableBucketVersioning {
  public static void disableBucketVersioning(String projectId, String bucketName) {
    // 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);
    bucket.toBuilder().setVersioningEnabled(false).build().update();

    System.out.println("Versioning is now disabled for bucket " + 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 enableBucketVersioning() {
  await storage.bucket(bucketName).setMetadata({
    versioning: {
      enabled: true,
    },
  });

  console.log(`Versioning is enabled for bucket ${bucketName}`);
}

enableBucketVersioning().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 disableBucketVersioning() {
  await storage.bucket(bucketName).setMetadata({
    versioning: {
      enabled: false,
    },
  });

  console.log(`Versioning is disabled for bucket ${bucketName}`);
}

disableBucketVersioning().catch(console.error);

PHP

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會啟用值區的物件版本管理功能:

use Google\Cloud\Storage\StorageClient;

/**
 * Enable versioning on the specified bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function enable_versioning(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'versioning' => [
            'enabled' => true,
        ]
    ]);

    printf('Versioning is now enabled for bucket %s', $bucketName);
}

下例示範如何停用值區的物件版本管理功能:

use Google\Cloud\Storage\StorageClient;

/**
 * Disable versioning of the given bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function disable_versioning(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'versioning' => [
            'enabled' => false,
        ]
    ]);

    printf('Versioning is now disabled for bucket %s', $bucketName);
}

Python

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會啟用值區的物件版本管理功能:

from google.cloud import storage


def enable_versioning(bucket_name):
    """Enable versioning for this bucket."""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.versioning_enabled = True
    bucket.patch()

    print(f"Versioning was enabled for bucket {bucket.name}")
    return bucket

下例示範如何停用值區的物件版本管理功能:

from google.cloud import storage


def disable_versioning(bucket_name):
    """Disable versioning for this bucket."""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.versioning_enabled = False
    bucket.patch()

    print(f"Versioning was disabled for bucket {bucket}")
    return bucket

Ruby

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會啟用值區的物件版本管理功能:

def enable_versioning 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.versioning = true

  puts "Versioning was enabled for bucket #{bucket_name}"
end

下例示範如何停用值區的物件版本管理功能:

def disable_versioning 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.versioning = false

  puts "Versioning was disabled for bucket #{bucket_name}"
end

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 建立包含下列資訊的 JSON 檔案:

    {
      "versioning": {
        "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=versioning"

    其中:

    • JSON_FILE_NAME 是您在步驟 2 建立的 JSON 檔案路徑。
    • BUCKET_NAME 是相關值區的名稱。例如:my-bucket

XML API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 建立包含下列資訊的 XML 檔案:

    <VersioningConfiguration>
      <Status>STATE</Status>
    </VersioningConfiguration>

    其中 STATEEnabledSuspended

  3. 使用 cURL 透過 PUT 值區要求和 versioning 查詢字串參數呼叫 XML API

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?versioning"

    其中:

    • XML_FILE_NAME 是您在步驟 2 建立的 XML 檔案路徑。
    • BUCKET_NAME 是相關值區的名稱。例如:my-bucket

啟用物件版本管理功能後,每當使用中的物件版本遭到取代或刪除,該版本就會成為非現行版本

確認是否已啟用物件版本管理功能

如要確認值區是否已啟用物件版本管理功能:

控制台

  1. 在 Google Cloud 控制台,前往「Cloud Storage bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,每個值區的物件版本控管狀態會顯示在「Protection」(保護) 欄中。

如果已啟用,系統會顯示「物件版本管理」文字。

指令列

使用加上 --format 旗標的 gcloud storage buckets describe 指令:

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

其中 BUCKET_NAME 是您要查看狀態的值區名稱。例如:my-bucket

如果成功且已啟用物件版本管理功能,回應會類似以下範例:

versioning:
  enabled: true

如果成功且未啟用物件版本管理功能,回應會類似以下範例:

null

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 GET Bucket 要求呼叫 JSON API

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

    其中 BUCKET_NAME 是相關值區的名稱。例如:my-bucket

如果成功且已啟用物件版本管理功能,回應會類似以下範例:

{
  "versioning": {
    "enabled": true
  }
}

如果成功且未啟用物件版本管理功能,回應會類似以下範例:

{}

XML API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 GET 值區要求和 versioning 查詢字串參數呼叫 XML API

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

    其中 BUCKET_NAME 是相關值區的名稱。例如:my-bucket

如果成功且已啟用物件版本管理功能,回應會類似以下範例:

<VersioningConfiguration>
  <Status>Enabled</Status>
</VersioningConfiguration>

如果成功且未啟用物件版本管理功能,回應會類似以下範例:

<VersioningConfiguration/>

後續步驟