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

概要 設定

このページでは、オブジェクトのバージョニングが有効になっている機能を持つバケットに通常適用される、非現行オブジェクトを一覧表示、アクセス、復元、削除する方法について説明します。

必要なロール

非現行オブジェクトの管理に必要な権限を取得するには、プロジェクトの Storage オブジェクト ユーザー(roles/storage.objectUser)の IAM ロールを付与するように管理者へ依頼してください。この事前定義ロールには、非現行オブジェクトの管理に必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

  • storage.objects.create
  • storage.objects.delete
  • storage.objects.get
  • storage.objects.list

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

プロジェクトでのロールの付与については、プロジェクトへのアクセス権の管理をご覧ください。

ユースケースによっては、追加の権限や代替のロールが必要になる場合があります。

  • このページのタスクを Google Cloud コンソールで実行する場合は、storage.buckets.list 権限も必要ですが、これは Storage オブジェクト ユーザー(roles/storage.objectUser)ロールには含まれていません。 この権限を取得するには、プロジェクトのストレージ管理者(roles/storage.admin)ロールを付与するように管理者へ依頼してください。

  • お使いのバケットに対するバケットレベルの統一アクセスが無効になっている場合、次のシナリオでは追加の権限が必要です。

    • 非現行オブジェクトをその ACL とともに返す場合は、storage.objects.getIamPolicy 権限も必要です。この権限は、Storage オブジェクト ユーザー(roles/storage.objectUser)ロールに含まれていません。この権限を取得するには、プロジェクトの Storage オブジェクト管理者(roles/storage.objectAdmin)ロールを付与するように管理者へ依頼してください。

    • ACL のある非現行オブジェクトの名前変更や復元を予定している場合は、storage.objects.setIamPolicy 権限も必要です。この権限は、Storage オブジェクト ユーザー(roles/storage.objectUser)ロールに含まれていません。この権限を取得するには、プロジェクトの Storage オブジェクト管理者(roles/storage.objectAdmin)ロールを付与するように管理者へ依頼してください。

非現行バージョンのオブジェクトを一覧表示する

オブジェクトのライブ バージョンと非現行バージョンの両方を一覧表示し、generation 番号を表示するには:

コンソール

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

    [バケット] に移動

  2. バケットのリストで、必要なオブジェクトを含むバケットの名前をクリックします。

    [バケットの詳細] ページが開き、[オブジェクト] タブが選択されています。

  3. フォルダ内にあるオブジェクトに移動します。

  4. 目的のオブジェクトの名前をクリックします。

    [オブジェクトの詳細] ページが開きます。[ライブ オブジェクト] タブが選択されています。

  5. [変更履歴] タブをクリックします。

コマンドライン

gcloud storage ls --all-versions コマンドを使用します。

gcloud storage ls --all-versions gs://BUCKET_NAME

BUCKET_NAME は、該当するバケットの名前です。例: my-bucket

次の例のようなレスポンスになります。

gs://BUCKET_NAME/OBJECT_NAME1#GENERATION_NUMBER1
gs://BUCKET_NAME/OBJECT_NAME2#GENERATION_NUMBER2
gs://BUCKET_NAME/OBJECT_NAME3#GENERATION_NUMBER3
...

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name) {
  for (auto&& object_metadata :
       client.ListObjects(bucket_name, gcs::Versions{true})) {
    if (!object_metadata) throw std::move(object_metadata).status();

    std::cout << "bucket_name=" << object_metadata->bucket()
              << ", object_name=" << object_metadata->name()
              << ", generation=" << object_metadata->generation() << "\n";
  }
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class ListFileArchivedGenerationSample
{
	public IEnumerable<Google.Apis.Storage.v1.Data.Object> ListFileArchivedGeneration(string bucketName = "your-bucket-name")
	{
		var storage = StorageClient.Create();

		var storageObjects = storage.ListObjects(bucketName, options: new ListObjectsOptions
		{
			Versions = true
		});

		foreach (var storageObject in storageObjects)
		{
			Console.WriteLine($"Filename: {storageObject.Name}, Generation: {storageObject.Generation}");
		}

		return storageObjects;
	}
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// listFilesAllVersion lists both live and noncurrent versions of objects within specified bucket.
func listFilesAllVersion(w io.Writer, bucket string) error {
	// bucket := "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()

	it := client.Bucket(bucket).Objects(ctx, &storage.Query{
		// Versions true to output all generations of objects
		Versions: true,
	})
	for {
		attrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Bucket(%q).Objects(): %w", bucket, err)
		}
		fmt.Fprintln(w, attrs.Name, attrs.Generation, attrs.Metageneration)
	}
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListObjectsWithOldVersions {
  public static void listObjectsWithOldVersions(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);
    Page<Blob> blobs = bucket.list(Storage.BlobListOption.versions(true));

    for (Blob blob : blobs.iterateAll()) {
      System.out.println(blob.getName() + "," + blob.getGeneration());
    }
  }
}

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 listFilesWithOldVersions() {
  const [files] = await storage.bucket(bucketName).getFiles({
    versions: true,
  });

  console.log('Files:');
  files.forEach(file => {
    console.log(file.name, file.generation);
  });
}

listFilesWithOldVersions().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

use Google\Cloud\Storage\StorageClient;

/**
 * List objects in a specified bucket with all archived generations.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function list_file_archived_generations(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $objects = $bucket->objects([
        'versions' => true,
    ]);

    foreach ($objects as $object) {
        print($object->name() . ',' . $object->info()['generation'] . PHP_EOL);
    }
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import storage


def list_file_archived_generations(bucket_name):
    """Lists all the blobs in the bucket with generation."""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()

    blobs = storage_client.list_blobs(bucket_name, versions=True)

    for blob in blobs:
        print(f"{blob.name},{blob.generation}")

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def list_file_archived_generations 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.files.each do |file|
    puts "#{file.name},#{file.generation}"
  end
end

REST API

JSON API

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

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

    ここで

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

非現行バージョンのオブジェクトには timeDeleted プロパティがあります。

XML API

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

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?versions&list-type=2"

    ここで

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

versions クエリ文字列パラメータを使用する場合と使用しない場合では、GET リクエストの結果にいくつかの違いが生じます。具体的には、リクエストに versions クエリ パラメータを含めると、Cloud Storage から次の情報が返されます。

  • 各オブジェクトに関する情報が含まれる Version 要素。
  • オブジェクトが非現行バージョンになった(削除や置換)時間を含む DeletedTime 要素。
  • 特定のオブジェクトが最新バージョンかどうかを示す IsLatest 要素。
  • オブジェクトのリストが部分的なリストである場合は、NextGenerationMarker 要素が返されます。これは、バケットに多数のオブジェクトのバージョンがある場合に発生します。最後のポイントから再開するには、後続のリクエストの generationmarker クエリ パラメータでこの要素の値を使用します。generationmarker クエリ パラメータは、marker クエリ パラメータを使用して、バージョニングされていないバケットのリストをページ割り付けするのと同じ方法で使用されます。

非現行バージョンのオブジェクトにアクセスする

オブジェクトのダウンロード、オブジェクトのメタデータの表示、オブジェクトのメタデータの更新などのタスクを実行するときにオブジェクトの非現行バージョンを使用するには:

コンソール

Google Cloud コンソールでは、非現行バージョンへの一般的なアクセス権は使用できません。Google Cloud コンソールでは、非現行バージョンの移動、コピー、復元削除のみを行うことができます。これらの操作は、オブジェクトの変更履歴リストから実行します。

コマンドライン

  1. オブジェクト名に、非現行バージョンの generation 番号を追加します。

    OBJECT_NAME#GENERATION_NUMBER

    ここで

    • OBJECT_NAME は、非現行バージョンの名前です。例: pets/dog.png
    • GENERATION_NUMBER は、非現行バージョンの世代番号です。例: 1560468815691234
  2. 手順 1 の文字列を使用して、通常のライブ バージョンのオブジェクトの場合と同じように処理します。

REST API

JSON API

  1. オブジェクトの URI に非現行バージョンの generation 番号を追加します。

    https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?generation=GENERATION_NUMBER

    ここで

    • BUCKET_NAME は、非現行バージョンを含むバケットの名前です。例: my-bucket
    • OBJECT_NAME は、URL エンコードされた非現行バージョンの名前です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png
    • GENERATION_NUMBER は、非現行バージョンの世代番号です。例: 1560468815691234
  2. 手順 1 の URI を使用して、通常のライブ バージョンのオブジェクトの場合と同じように処理します。

XML API

  1. オブジェクトの URI に非現行バージョンの generation 番号を追加します。

    https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME?generation=GENERATION_NUMBER

    ここで

    • BUCKET_NAME は、非現行バージョンを含むバケットの名前です。例: my-bucket
    • OBJECT_NAME は、URL エンコードされた非現行バージョンの名前です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png
    • GENERATION_NUMBER は、非現行バージョンの世代番号です。例: 1560468815691234
  2. 手順 1 の URI を使用して、通常のライブ バージョンのオブジェクトの場合と同じように処理します。

非現行バージョンのオブジェクトを復元する

Cloud Storage で非現行バージョンのオブジェクトを復元するには、そのオブジェクトのコピーを作成します。この操作を行うと、コピーがライブ バージョンになり、実質的にバージョンが復元されます。すでにライブ バージョンがあり、バケットのオブジェクト バージョニングが有効になっている場合、非現行バージョンを復元すると、それまでのライブ バージョンは非現行になります。

コンソール

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

    [バケット] に移動

  2. バケットのリストで、必要なオブジェクトを含むバケットの名前をクリックします。

    [バケットの詳細] ページが開き、[オブジェクト] タブが選択されています。

    非現行オブジェクトを表示するには、[削除されたデータを表示] トグルをクリックします。

  3. フォルダ内にあるオブジェクトに移動します。

  4. 目的のオブジェクトの名前をクリックします。

    [オブジェクトの詳細] ページが開きます。[ライブ オブジェクト] タブが選択されています。

  5. [変更履歴] タブをクリックします。

  6. 必要なバージョンの [復元] ボタンをクリックします。

    オブジェクト バージョンの復元ペインが開きます。

  7. [確認] をクリックします。

コマンドライン

gcloud storage cp コマンドを使用します。

gcloud storage cp gs://BUCKET_NAME/OBJECT_NAME#GENERATION_NUMBER gs://BUCKET_NAME/OBJECT_NAME

ここで

  • BUCKET_NAME は、復元する非現行バージョンを含むバケットの名前です。例: my-bucket
  • OBJECT_NAME は、復元する非現行バージョンの名前です。例: pets/dog.png
  • GENERATION_NUMBER は、復元する非現行バージョンの世代番号です。例: 1560468815691234

成功した場合は、次の例のようなレスポンスになります。

Operation completed over 1 objects/58.8 KiB.

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
   std::string const& source_object_name,
   std::string const& destination_bucket_name,
   std::string const& destination_object_name,
   std::int64_t source_object_generation) {
  StatusOr<gcs::ObjectMetadata> copy =
      client.CopyObject(source_bucket_name, source_object_name,
                        destination_bucket_name, destination_object_name,
                        gcs::SourceGeneration{source_object_generation});
  if (!copy) throw std::move(copy).status();

  std::cout << "Successfully copied " << source_object_name << " generation "
            << source_object_generation << " in bucket " << source_bucket_name
            << " to bucket " << copy->bucket() << " with name "
            << copy->name()
            << ".\nThe full metadata after the copy is: " << *copy << "\n";
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


using Google.Cloud.Storage.V1;
using System;

public class CopyFileArchivedGenerationSample
{
    public Google.Apis.Storage.v1.Data.Object CopyFileArchivedGeneration(
        string sourceBucketName = "source-bucket-name",
        string sourceObjectName = "source-file",
        string destBucketName = "destination-bucket-name",
        string destObjectName = "destination-file-name",
        long? generation = 1579287380533984)
    {
        var storage = StorageClient.Create();
        var copyOptions = new CopyObjectOptions
        {
            SourceGeneration = generation
        };

        var copiedFile = storage.CopyObject(sourceBucketName, sourceObjectName,
            destBucketName, destObjectName, copyOptions);

        Console.WriteLine($"Generation {generation} of the object {sourceBucketName}/{sourceObjectName} " +
            $"was copied to to {destBucketName}/{destObjectName}.");

        return copiedFile;
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

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

// copyOldVersionOfObject copies a noncurrent version of an object.
func copyOldVersionOfObject(w io.Writer, bucket, srcObject, dstObject string, gen int64) error {
	// bucket := "bucket-name"
	// srcObject := "source-object-name"
	// dstObject := "destination-object-name"

	// gen is the generation of srcObject to copy.
	// gen := 1587012235914578
	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()

	src := client.Bucket(bucket).Object(srcObject)
	dst := client.Bucket(bucket).Object(dstObject)

	// Optional: set a generation-match precondition to avoid potential race
	// conditions and data corruptions. The request to copy is aborted if the
	// object's generation number does not match your precondition.
	// For a dst object that does not yet exist, set the DoesNotExist precondition.
	dst = dst.If(storage.Conditions{DoesNotExist: true})
	// If the destination object already exists in your bucket, set instead a
	// generation-match precondition using its generation number.
	// attrs, err := dst.Attrs(ctx)
	// if err != nil {
	// 	return fmt.Errorf("object.Attrs: %w", err)
	// }
	// dst = dst.If(storage.Conditions{GenerationMatch: attrs.Generation})

	if _, err := dst.CopierFrom(src.Generation(gen)).Run(ctx); err != nil {
		return fmt.Errorf("Object(%q).CopierFrom(%q).Generation(%v).Run: %w", dstObject, srcObject, gen, err)
	}
	fmt.Fprintf(w, "Generation %v of object %v in bucket %v was copied to %v\n", gen, srcObject, bucket, dstObject)
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

public class CopyOldVersionOfObject {
  public static void copyOldVersionOfObject(
      String projectId,
      String bucketName,
      String objectToCopy,
      long generationToCopy,
      String newObjectName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of the GCS object to copy an old version of
    // String objectToCopy = "your-object-name";

    // The generation of objectToCopy to copy
    // long generationToCopy = 1579287380533984;

    // What to name the new object with the old data from objectToCopy
    // String newObjectName = "your-new-object";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    // Optional: set a generation-match precondition to avoid potential race
    // conditions and data corruptions. The request returns a 412 error if the
    // preconditions are not met.
    Storage.BlobTargetOption precondition;
    if (storage.get(bucketName, newObjectName) == null) {
      // For a target object that does not yet exist, set the DoesNotExist precondition.
      // This will cause the request to fail if the object is created before the request runs.
      precondition = Storage.BlobTargetOption.doesNotExist();
    } else {
      // If the destination already exists in your bucket, instead set a generation-match
      // precondition. This will cause the request to fail if the existing object's generation
      // changes before the request runs.
      precondition =
          Storage.BlobTargetOption.generationMatch(
              storage.get(bucketName, newObjectName).getGeneration());
    }

    Storage.CopyRequest copyRequest =
        Storage.CopyRequest.newBuilder()
            .setSource(BlobId.of(bucketName, objectToCopy, generationToCopy))
            .setTarget(BlobId.of(bucketName, newObjectName), precondition)
            .build();
    storage.copy(copyRequest);

    System.out.println(
        "Generation "
            + generationToCopy
            + " of object "
            + objectToCopy
            + " in bucket "
            + bucketName
            + " was copied to "
            + newObjectName);
  }
}

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 srcBucketName = "your-unique-bucket-name";

// The ID of the GCS file to copy an old version of
// const srcFilename = "your-file-name";

// The generation of fileToCopy to copy
// const generation = 1579287380533984;

// The ID of the bucket to copy the file to
// const destBucketName = 'target-file-bucket';

// What to name the new file with the old data from srcFilename
// const destFileName = "your-new-file";

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function copyOldVersionOfFile() {
  // Copies the file to the other bucket

  // Optional:
  // Set a generation-match precondition to avoid potential race conditions
  // and data corruptions. The request to copy is aborted if the object's
  // generation number does not match your precondition. For a destination
  // object that does not yet exist, set the ifGenerationMatch precondition to 0
  // If the destination object already exists in your bucket, set instead a
  // generation-match precondition using its generation number.
  const copyOptions = {
    preconditionOpts: {
      ifGenerationMatch: destinationGenerationMatchPrecondition,
    },
  };

  await storage
    .bucket(srcBucketName)
    .file(srcFilename, {
      generation,
    })
    .copy(storage.bucket(destBucketName).file(destFileName), copyOptions);

  console.log(
    `Generation ${generation} of file ${srcFilename} in bucket ${srcBucketName} was copied to ${destFileName} in bucket ${destBucketName}`
  );
}

copyOldVersionOfFile().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

use Google\Cloud\Storage\StorageClient;

/**
 * Copy archived generation of a given object to a new object.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectToCopy The name of the object to copy.
 *        (e.g. 'my-object')
 * @param string $generationToCopy The generation of the object to copy.
 *        (e.g. 1579287380533984)
 * @param string $newObjectName The name of the target object.
 *        (e.g. 'my-object-1579287380533984')
 */
function copy_file_archived_generation(string $bucketName, string $objectToCopy, string $generationToCopy, string $newObjectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $object = $bucket->object($objectToCopy, [
        'generation' => $generationToCopy,
    ]);

    $object->copy($bucket, [
        'name' => $newObjectName,
    ]);

    printf(
        'Generation %s of object %s in bucket %s was copied to %s',
        $generationToCopy,
        $objectToCopy,
        $bucketName,
        $newObjectName
    );
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import storage


def copy_file_archived_generation(
        bucket_name, blob_name, destination_bucket_name, destination_blob_name, generation
):
    """Copies a blob from one bucket to another with a new name with the same generation."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"
    # destination_bucket_name = "destination-bucket-name"
    # destination_blob_name = "destination-object-name"
    # generation = 1579287380533984

    storage_client = storage.Client()

    source_bucket = storage_client.bucket(bucket_name)
    source_blob = source_bucket.blob(blob_name)
    destination_bucket = storage_client.bucket(destination_bucket_name)

    # Optional: set a generation-match precondition to avoid potential race conditions
    # and data corruptions. The request to copy is aborted if the object's
    # generation number does not match your precondition. For a destination
    # object that does not yet exist, set the if_generation_match precondition to 0.
    # If the destination object already exists in your bucket, set instead a
    # generation-match precondition using its generation number.
    destination_generation_match_precondition = 0

    # source_generation selects a specific revision of the source object, as opposed to the latest version.
    blob_copy = source_bucket.copy_blob(
        source_blob, destination_bucket, destination_blob_name, source_generation=generation, if_generation_match=destination_generation_match_precondition
    )

    print(
        "Generation {} of the blob {} in bucket {} copied to blob {} in bucket {}.".format(
            generation,
            source_blob.name,
            source_bucket.name,
            blob_copy.name,
            destination_bucket.name,
        )
    )

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def copy_file_archived_generation source_bucket_name:,
                                  source_file_name:,
                                  generation:,
                                  destination_bucket_name:,
                                  destination_file_name:
  # The ID of the bucket the original object is in
  # source_bucket_name = "source-bucket-name"

  # The ID of the GCS object to copy
  # source_file_name = "source-file-name"

  # The generation of your GCS object to copy
  # generation = 1579287380533984

  # The ID of the bucket to copy the object to
  # destination_bucket_name = "destination-bucket-name"

  # The ID of the new GCS object
  # destination_file_name = "destination-file-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

  source_bucket = storage.bucket source_bucket_name, skip_lookup: true
  source_file = source_bucket.file source_file_name
  destination_bucket = storage.bucket destination_bucket_name, skip_lookup: true

  destination_file = source_file.copy destination_bucket, destination_file_name, generation: generation

  puts "Generation #{generation} of the file #{source_file.name} in bucket #{source_bucket.name} copied to file " \
       "#{destination_file.name} in bucket #{destination_bucket.name}"
end

REST API

JSON API

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

    curl -X POST \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Length: 0" \
      "https://storage.googleapis.com/upload/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME/rewriteTo/b/BUCKET_NAME/o/OBJECT_NAME?sourceGeneration=GENERATION_NUMBER"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • BUCKET_NAME は、復元する非現行バージョンを含むバケットの名前です。例: my-bucket
    • OBJECT_NAME は、復元する非現行バージョンの URL エンコード名です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png
    • GENERATION_NUMBER は、復元する非現行バージョンの世代番号です。例: 1560468815691234

XML API

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

    curl -X PUT \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "x-goog-copy-source: BUCKET_NAME/OBJECT_NAME" \
      -H "x-goog-copy-source-generation:GENERATION_NUMBER" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • BUCKET_NAME は、復元する非現行バージョンを含むバケットの名前です。例: my-bucket
    • OBJECT_NAME は、復元する非現行バージョンの URL エンコード名です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png
    • GENERATION_NUMBER は、復元する非現行バージョンの世代番号です。例: 1560468815691234

オブジェクト バージョンを復元した後、元の非現行バージョンはバケットに存在し続けます。非現行バージョンが不要な場合は、すぐに削除することも、指定した条件を満たしたときに削除されるようオブジェクト ライフサイクル管理を構成することもできます。

非現行バージョンのオブジェクトを削除する

コンソール

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

    [バケット] に移動

  2. バケットのリストで、必要なオブジェクトを含むバケットの名前をクリックします。

    [バケットの詳細] ページが開き、[オブジェクト] タブが選択されています。

  3. フォルダ内にあるオブジェクトに移動します。

  4. 目的のオブジェクトの名前をクリックします。

    [オブジェクトの詳細] ページが開きます。[ライブ オブジェクト] タブが選択されています。

  5. [変更履歴] タブをクリックします。

  6. 必要なバージョンのチェックボックスをオンにします。

  7. [削除] ボタンをクリックします。

    バージョンの削除ペインが開きます。

  8. オブジェクトの削除を確認するため、テキスト フィールドに「delete」と入力します。

  9. [削除] をクリックします。

コマンドライン

gcloud storage rm コマンドを使用します。

gcloud storage rm gs://BUCKET_NAME/OBJECT_NAME#GENERATION_NUMBER

ここで

  • BUCKET_NAME は、削除する非現行バージョンを含むバケットの名前です。例: my-bucket
  • OBJECT_NAME は、削除する非現行バージョンの名前です。例: pets/dog.png
  • GENERATION_NUMBER は、削除する非現行バージョンの世代番号です。例: 1560468815691234

成功した場合は、次の例のようなレスポンスになります。

Operation completed over 1 objects.

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::int64_t object_generation) {
  google::cloud::Status status = client.DeleteObject(
      bucket_name, object_name, gcs::Generation{object_generation});
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "Deleted " << object_name << " generation "
            << object_generation << " in bucket " << bucket_name << "\n";
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


using Google.Cloud.Storage.V1;
using System;

public class DeleteFileArchivedGenerationSample
{
    public void DeleteFileArchivedGeneration(
        string bucketName = "your-bucket-name",
        string objectName = "your-object-name",
        long? generation = 1579287380533984)
    {
        var storage = StorageClient.Create();

        storage.DeleteObject(bucketName, objectName, new DeleteObjectOptions
        {
            Generation = generation
        });

        Console.WriteLine($"Generation ${generation} of file {objectName} was deleted from bucket {bucketName}.");
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

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

// deleteOldVersionOfObject deletes a noncurrent version of an object.
func deleteOldVersionOfObject(w io.Writer, bucketName, objectName string, gen int64) error {
	// bucketName := "bucket-name"
	// objectName := "object-name"

	// gen is the generation of objectName to delete.
	// gen := 1587012235914578
	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()

	obj := client.Bucket(bucketName).Object(objectName)
	if err := obj.Generation(gen).Delete(ctx); err != nil {
		return fmt.Errorf("Bucket(%q).Object(%q).Generation(%v).Delete: %w", bucketName, objectName, gen, err)
	}
	fmt.Fprintf(w, "Generation %v of object %v was deleted from %v\n", gen, objectName, bucketName)
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

public class DeleteOldVersionOfObject {
  public static void deleteOldVersionOfObject(
      String projectId, String bucketName, String objectName, long generationToDelete) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    // The generation of objectName to delete
    // long generationToDelete = 1579287380533984;

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    storage.delete(BlobId.of(bucketName, objectName, generationToDelete));

    System.out.println(
        "Generation "
            + generationToDelete
            + " of object "
            + objectName
            + " was deleted from "
            + 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';

// The ID of your GCS file
// const fileName = 'your-file-name';

// The generation of fileName to delete
// const generation = 1579287380533984;

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function deleteOldVersionOfFile() {
  // Deletes the file from the bucket with given version
  await storage
    .bucket(bucketName)
    .file(fileName, {
      generation,
    })
    .delete();

  console.log(
    `Generation ${generation} of file ${fileName} was deleted from ${bucketName}`
  );
}

deleteOldVersionOfFile().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an archived generation of the given object.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $generationToDelete the generation of the object to delete.
 *        (e.g. 1579287380533984)
 */
function delete_file_archived_generation(string $bucketName, string $objectName, string $generationToDelete): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $object = $bucket->object($objectName, [
        'generation' => $generationToDelete,
    ]);

    $object->delete();

    printf(
        'Generation %s of object %s was deleted from %s',
        $generationToDelete,
        $objectName,
        $bucketName
    );
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import storage


def delete_file_archived_generation(bucket_name, blob_name, generation):
    """Delete a blob in the bucket with the given generation."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"
    # generation = 1579287380533984

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.delete_blob(blob_name, generation=generation)
    print(
        f"Generation {generation} of blob {blob_name} was deleted from {bucket_name}"
    )

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def delete_file_archived_generation bucket_name:, file_name:, generation:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  # The generation of the file to delete
  # generation = 1579287380533984

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name, skip_lookup: true

  file = bucket.file file_name

  file.delete generation: generation

  puts "Generation #{generation} of file #{file_name} was deleted from #{bucket_name}"
end

REST API

JSON API

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

    curl -X DELETE \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?generation=GENERATION_NUMBER"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • BUCKET_NAME は、削除する非現行バージョンを含むバケットの名前です。例: my-bucket
    • OBJECT_NAME は、削除する非現行バージョンの URL エンコード名です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png
    • GENERATION_NUMBER は、削除する非現行バージョンの世代番号です。例: 1560468815691234

XML API

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

    curl -X DELETE \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME?generation=GENERATION_NUMBER"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • BUCKET_NAME は、削除する非現行バージョンを含むバケットの名前です。例: my-bucket
    • OBJECT_NAME は、削除する非現行バージョンの URL エンコード名です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png
    • GENERATION_NUMBER は、削除する非現行バージョンの世代番号です。例: 1560468815691234

次のステップ