オブジェクトを削除する

このページでは、Cloud Storage のバケットからオブジェクトを削除する方法を説明します。

必要なロール

オブジェクトの削除に必要な権限を取得するには、削除するオブジェクトを含むバケットに対するストレージ オブジェクト ユーザー(roles/storage.objectUser)の IAM ロールを付与するよう管理者に依頼してください。

このページで説明するタスクを Google Cloud コンソールを使って実施する場合は、Storage オブジェクト ユーザー(roles/storage.objectUser)ロールの代わりにストレージ管理者(roles/storage.admin)のロールを付与するか、Storage オブジェクト ユーザー(roles/storage.objectUser)ロールに加えて基本ロールである閲覧者(roles/viewer)を付与するように管理者に依頼してください。

これらのロールには、オブジェクトの削除に必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

  • storage.objects.delete
  • storage.objects.list
    • この権限は、 Google Cloud コンソールを使用する場合、または Google Cloud CLI で --recursive フラグやワイルドカードを使用する場合にのみ必要です。
  • storage.buckets.list
    • この権限は、このページで説明する操作を Google Cloud コンソールで行う場合にのみ必要です。

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

バケットに対するロールの付与については、バケットでの IAM ポリシーの設定と管理をご覧ください。

オブジェクトを削除する

いずれかの Cloud Storage バケットからオブジェクトを削除するには、次の手順を行います。

コンソール

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

    [バケット] に移動

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

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

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

  4. 削除する各オブジェクトのチェックボックスをオンにします。

    フォルダのチェックボックスをオンにすると、そのフォルダ内のすべてのオブジェクトが削除されます。

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

  6. 表示されたダイアログで [削除] をクリックします。

多くのオブジェクトを一度に削除する場合は、 Google Cloud コンソールで通知アイコンをクリックして削除の進捗状況を追跡できます。Google Cloud コンソールでは、最大数百万個のオブジェクトをバックグラウンドで一括削除できます。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

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

gcloud storage rm gs://BUCKET_NAME/OBJECT_NAME

ここで

  • BUCKET_NAME は、削除するオブジェクトが格納されているバケットの名前です。例: my-bucket
  • OBJECT_NAME は、削除するオブジェクトの名前です。例: pets/dog.png

正常に終了すると、レスポンスは次の例のようになります。

Removing objects: Removing gs://example-bucket/file.txt...   Completed 1/1

クライアント ライブラリ

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) {   google::cloud::Status status =       client.DeleteObject(bucket_name, object_name);    if (!status.ok()) throw std::runtime_error(status.message());   std::cout << "Deleted " << object_name << " in bucket " << bucket_name             << "\n"; }

C#

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

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

 using Google.Cloud.Storage.V1; using System;  public class DeleteFileSample {     public void DeleteFile(         string bucketName = "your-unique-bucket-name",         string objectName = "your-object-name")     {         var storage = StorageClient.Create();         storage.DeleteObject(bucketName, objectName);         Console.WriteLine($"Deleted {objectName}.");     } }

Go

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

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

import ( 	"context" 	"fmt" 	"io" 	"time"  	"cloud.google.com/go/storage" )  // deleteFile removes specified object. func deleteFile(w io.Writer, bucket, object string) error { 	// bucket := "bucket-name" 	// object := "object-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()  	o := client.Bucket(bucket).Object(object)  	// Optional: set a generation-match precondition to avoid potential race 	// conditions and data corruptions. The request to delete the file is aborted 	// if the object's generation number does not match your precondition. 	attrs, err := o.Attrs(ctx) 	if err != nil { 		return fmt.Errorf("object.Attrs: %w", err) 	} 	o = o.If(storage.Conditions{GenerationMatch: attrs.Generation})  	if err := o.Delete(ctx); err != nil { 		return fmt.Errorf("Object(%q).Delete: %w", object, err) 	} 	fmt.Fprintf(w, "Blob %v deleted.\n", object) 	return nil } 

Java

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

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

import com.google.cloud.storage.Blob; import com.google.cloud.storage.BlobId; import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageOptions;  public class DeleteObject {   public static void deleteObject(String projectId, String bucketName, String objectName) {     // 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";      Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();     Blob blob = storage.get(bucketName, objectName);     if (blob == null) {       System.out.println("The object " + objectName + " wasn't found in " + bucketName);       return;     }     BlobId idWithGeneration = blob.getBlobId();     // Deletes the blob specified by its id. When the generation is present and non-null it will be     // specified in the request.     // If versioning is enabled on the bucket and the generation is present in the delete request,     // only the version of the object with the matching generation will be deleted.     // If instead you want to delete the current version, the generation should be dropped by     // performing the following.     // BlobId idWithoutGeneration =     //    BlobId.of(idWithGeneration.getBucket(), idWithGeneration.getName());     // storage.delete(idWithoutGeneration);     storage.delete(idWithGeneration);      System.out.println("Object " + objectName + " was permanently 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';  // Imports the Google Cloud client library const {Storage} = require('@google-cloud/storage');  // Creates a client const storage = new Storage();  // Optional: // Set a generation-match precondition to avoid potential race conditions // and data corruptions. The request to delete 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 deleteOptions = {   ifGenerationMatch: generationMatchPrecondition, }; async function deleteFile() {   await storage.bucket(bucketName).file(fileName).delete(deleteOptions);    console.log(`gs://${bucketName}/${fileName} deleted`); }  deleteFile().catch(console.error);

PHP

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

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

use Google\Cloud\Storage\StorageClient;  /**  * Delete an 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')  */ function delete_object(string $bucketName, string $objectName): void {     $storage = new StorageClient();     $bucket = $storage->bucket($bucketName);     $object = $bucket->object($objectName);     $object->delete();     printf('Deleted gs://%s/%s' . PHP_EOL, $bucketName, $objectName); }

Python

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

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

from google.cloud import storage   def delete_blob(bucket_name, blob_name):     """Deletes a blob from the bucket."""     # bucket_name = "your-bucket-name"     # blob_name = "your-object-name"      storage_client = storage.Client()      bucket = storage_client.bucket(bucket_name)     blob = bucket.blob(blob_name)     generation_match_precondition = None      # Optional: set a generation-match precondition to avoid potential race conditions     # and data corruptions. The request to delete is aborted if the object's     # generation number does not match your precondition.     blob.reload()  # Fetch blob metadata to use in generation_match_precondition.     generation_match_precondition = blob.generation      blob.delete(if_generation_match=generation_match_precondition)      print(f"Blob {blob_name} deleted.")  

Ruby

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

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

def delete_file bucket_name:, file_name:   # The ID of your GCS bucket   # bucket_name = "your-unique-bucket-name"    # The ID of your GCS object   # file_name = "your-file-name"    require "google/cloud/storage"    storage = Google::Cloud::Storage.new   bucket  = storage.bucket bucket_name, skip_lookup: true   file    = bucket.file file_name    file.delete    puts "Deleted #{file.name}" end

REST API

JSON API

  1. gcloud CLI のインストールと初期化を行います。これにより、Authorization ヘッダーのアクセス トークンを生成できます。

  2. cURL使用して、DELETEリクエストで JSON API を呼び出します。

    curl -X DELETE \   -H "Authorization: Bearer $(gcloud auth print-access-token)" \   "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME"

    ここで

    • BUCKET_NAME は、削除するオブジェクトが格納されているバケットの名前です。例: my-bucket
    • OBJECT_NAME は、削除するオブジェクトの URL エンコード名です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png

XML API

  1. gcloud CLI のインストールと初期化を行います。これにより、Authorization ヘッダーのアクセス トークンを生成できます。

  2. cURL使用して、DELETE Objectリクエストで XML API を呼び出します。

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

    ここで

    • BUCKET_NAME は、削除するオブジェクトが格納されているバケットの名前です。例: my-bucket
    • OBJECT_NAME は、削除するオブジェクトの URL エンコード名です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png

オブジェクトを一括で削除する

数十万個以上のオブジェクトを一括削除する場合は、処理に非常に時間がかかるため、gcloud storage の使用を避けてください。代わりに、次のいずれかの方法を検討してください。

  • オブジェクトのライフサイクル管理機能を使用すると、任意の数のオブジェクトを削除できます。この機能を使用してバケット内のオブジェクトを一括削除するには、条件の Age が 0 に設定され、アクションが delete に設定されているライフサイクル構成ルールを設定します。ルールを設定すると、Cloud Storage は非同期で一括削除を実行します。

  • 削除するオブジェクトが 100 万個までであれば、 Google Cloud コンソールの使用も推奨されます。このような削除リクエストを開始すると、プロセスはバックグラウンドで行われます。一括削除のステータスを確認するには、 Google Cloud コンソールのヘッダーにある通知ボタン()をクリックします。

  • 特定のクライアント ライブラリを使用する場合、または JSON API を直接使用する場合は、削除リクエストをバッチ処理すると、作成する必要がある HTTP 接続の数を削減できます。

次のステップ