オブジェクトのバージョニングを使用する

概要 用途

このページでは、バケットのオブジェクト バージョニングの有効化、無効化、およびステータスの確認を行う方法について説明します。オブジェクトのバージョニングによって保持されているオブジェクトを一覧表示、復元、削除する方法については、バージョニングされたオブジェクトの使用をご覧ください。

必要なロール

バケットでオブジェクトのバージョニングの設定と管理に必要な権限を取得するには、バケットまたはバケットを含むプロジェクトに対するストレージ管理者(roles/storage.admin)IAM ロールを付与するよう管理者に依頼してください。この事前定義ロールには、バケットのオブジェクトのバージョニングの設定と管理に必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

  • storage.buckets.get
  • storage.buckets.update
  • storage.buckets.list
    • この権限は、Google Cloud コンソールを使用してこのページの手順を実施する場合にのみ必要です。

カスタムロールを使用して、これらの権限を取得することもできます。

バケットのロールの付与については、バケットで IAM を使用するをご覧ください。プロジェクトに対するロールの付与については、プロジェクトへのアクセス権を管理するをご覧ください。

バケットでオブジェクトのバージョニングを設定する

コンソール

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットのリストで、オブジェクトのバージョニングを有効または無効にするバケットの名前をクリックします。

  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. OAuth 2.0 Playground から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. 次の情報が含まれる JSON ファイルを作成します。

    {
      "versioning": {
        "enabled": STATE
      }
    }

    ここで、STATEtrue または false です。

  3. cURL を使用して JSON API を呼び出し、PATCH Bucket リクエストを行います。

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

    ここで

    • JSON_FILE_NAME は、手順 2 で作成した JSON ファイルのパスです。
    • OAUTH2_TOKEN は、手順 1 で作成したアクセス トークンです。
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

XML API

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. 次の情報が含まれる XML ファイルを作成します。

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

    ここで、STATEEnabled または Suspended です。

  3. cURL を使用して、PUT Bucket リクエストと versioning クエリ文字列パラメータを含めた XML API を呼び出します。

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?versioning"

    ここで

    • XML_FILE_NAME は、手順 2 で作成した XML ファイルのパスです。
    • OAUTH2_TOKEN は、手順 1 で作成したアクセス トークンです。
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

オブジェクトのバージョニングが有効になると、オブジェクトのライブ バージョンが置換または削除されるたびに、そのバージョンが非現行バージョンになります。

オブジェクトのバージョニングが有効になっているかどうかを確認する

バケットでオブジェクトのバージョニングが有効になっているかどうかを確認するには:

コンソール

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットリストの [保護] 列に、各バケットのオブジェクトのバージョニングのステータスが表示されます。

有効の場合は、[オブジェクトのバージョニング] というテキストが表示されます。

コマンドライン

gcloud storage buckets describe コマンドを使用し、--format フラグを指定します。

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

ここで、BUCKET_NAME はステータスを表示するバケットの名前です。例: my-bucket

成功してオブジェクトのバージョニングが有効になっている場合、レスポンスは次の例のようになります。

versioning:
  enabled: true

成功してオブジェクトのバージョニングが有効になっていない場合、レスポンスは次の例のようになります。

null

REST API

JSON API

  1. OAuth 2.0 Playground から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. cURL を使用して JSON API を呼び出し、GET Bucket リクエストを行います。

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

    ここで

    • OAUTH2_TOKEN は、手順 1 で作成したアクセス トークンです。
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

成功してオブジェクトのバージョニングが有効になっている場合、レスポンスは次の例のようになります。

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

成功してオブジェクトのバージョニングが有効になっていない場合、レスポンスは次の例のようになります。

{}

XML API

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. cURL を使用して、GET Bucket リクエストと versioning クエリ文字列パラメータを含めた XML API を呼び出します。

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?versioning"

    ここで

    • OAUTH2_TOKEN は、手順 1 で作成したアクセス トークンです。
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

成功してオブジェクトのバージョニングが有効になっている場合、レスポンスは次の例のようになります。

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

成功してオブジェクトのバージョニングが有効になっていない場合、レスポンスは次の例のようになります。

<VersioningConfiguration/>

次のステップ