Menghapus objek

Halaman ini menunjukkan cara menghapus objek dari bucket Anda di Cloud Storage. Untuk mengetahui ringkasan metode penghapusan objek, lihat Tentang penghapusan objek.

Peran yang diperlukan

Untuk mendapatkan izin yang Anda perlukan untuk menghapus objek, minta administrator untuk memberi Anda peran IAM berikut pada bucket yang berisi objek yang ingin Anda hapus:

  • Menghapus objek menggunakan Google Cloud CLI atau REST API: Pengguna Objek Storage (roles/storage.objectUser)
  • Menghapus objek menggunakan konsol Google Cloud : Admin Penyimpanan (roles/storage.admin)
  • Atau, untuk menghapus objek menggunakan konsol Google Cloud : Viewer (roles/viewer) dan Storage Object User (roles/storage.objectUser)

Untuk mengetahui informasi selengkapnya tentang pemberian peran, lihat Mengelola akses ke project, folder, dan organisasi.

Peran bawaan ini berisi izin yang diperlukan untuk menghapus objek. Untuk melihat izin yang benar-benar diperlukan, perluas bagian Izin yang diperlukan:

Izin yang diperlukan

Izin berikut diperlukan untuk menghapus objek:

  • Menghapus objek: storage.objects.delete
  • Mencantumkan objek menggunakan konsol Google Cloud , atau menggunakan flag --recursive atau karakter pengganti di Google Cloud CLI: storage.objects.list
  • Mencantumkan bucket menggunakan konsol Google Cloud : storage.buckets.list

Anda mungkin juga bisa mendapatkan izin ini dengan peran khusus atau peran bawaan lainnya.

Menghapus satu objek

Bagian ini menunjukkan cara menghapus satu objek dalam satu waktu.

Selesaikan langkah-langkah berikut untuk menghapus satu objek:

Konsol

  1. Di konsol Google Cloud , buka halaman Buckets Cloud Storage.

    Buka Buckets

  2. Dalam daftar bucket, klik nama bucket yang berisi objek yang ingin dihapus.

    Halaman Detail bucket akan terbuka, dan tab Objek akan dipilih.

  3. Buka objek, yang mungkin terletak dalam folder.

  4. Pilih kotak centang untuk objek yang ingin Anda hapus.

  5. Klik Hapus, lalu klik Hapus di dialog yang muncul.

Command line

Gunakan perintah Google Cloud CLI gcloud storage rm:

gcloud storage rm gs://BUCKET_NAME/OBJECT_NAME

Dengan keterangan:

  • BUCKET_NAME adalah nama bucket yang berisi objek yang ingin Anda hapus. Contoh, my-bucket.
  • OBJECT_NAME adalah nama objek yang ingin Anda hapus. Contoh, pets/dog.png.

Jika berhasil, responsnya akan terlihat mirip dengan contoh berikut:

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

Library klien

C++

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C++ API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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#

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C# API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.


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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Go API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Java API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Node.js API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

/**
 * 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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage PHP API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Python API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Ruby API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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

Rust

use google_cloud_storage::client::StorageControl;

pub async fn sample(client: &StorageControl, bucket_id: &str) -> anyhow::Result<()> {
    const NAME: &str = "deleted-object-name";
    client
        .delete_object()
        .set_bucket(format!("projects/_/buckets/{bucket_id}"))
        .set_object(NAME)
        // Consider .set_generation() to make request idempotent
        .send()
        .await?;
    println!("successfully deleted object {NAME} in bucket {bucket_id}");
    Ok(())
}

REST API

JSON API

  1. Instal dan lakukan inisialisasigcloud CLI, yang memungkinkan Anda membuat token akses untuk header Authorization.

  2. Gunakan curl untuk memanggil JSON API dengan permintaan DELETE:

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

    Dengan:

    • BUCKET_NAME adalah nama bucket yang berisi objek yang ingin Anda hapus. Contoh, my-bucket.
    • OBJECT_NAME adalah nama objek yang dienkode ke URL yang ingin Anda hapus. Contohnya, pets/dog.png, yang berenkode URL menjadi pets%2Fdog.png.

XML API

  1. Instal dan lakukan inisialisasigcloud CLI, yang memungkinkan Anda membuat token akses untuk header Authorization.

  2. Gunakan curl untuk memanggil XML API dengan permintaan DELETE Object:

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

    Dengan:

    • BUCKET_NAME adalah nama bucket yang berisi objek yang ingin Anda hapus. Contoh, my-bucket.
    • OBJECT_NAME adalah nama objek yang dienkode ke URL yang ingin Anda hapus. Contohnya, pets/dog.png, yang berenkode URL menjadi pets%2Fdog.png.

Menghapus objek secara massal

Bagian ini menunjukkan cara menghapus objek secara massal dengan memilihnya di konsolGoogle Cloud , dengan menghapus objek dengan awalan umum menggunakan alat command line, atau dengan menentukan daftar objek dalam permintaan API atau library klien.

Konsol

  1. Di konsol Google Cloud , buka halaman Buckets Cloud Storage.

    Buka Buckets

  2. Dalam daftar bucket, klik nama bucket yang berisi objek yang ingin dihapus.

    Halaman Detail bucket akan terbuka, dan tab Objek akan dipilih.

  3. Buka objek, yang mungkin berada dalam folder.

  4. Centang kotak untuk setiap objek yang ingin Anda hapus.

    Anda dapat memilih kotak centang untuk folder, yang akan menghapus semua objek yang ada dalam folder tersebut.

  5. Klik Hapus, lalu klik Hapus di dialog yang muncul.

Jika menghapus banyak objek sekaligus, Anda dapat melacak progres penghapusan dengan mengklik ikon Notifications di konsol Google Cloud . KonsolGoogle Cloud dapat menghapus hingga beberapa juta objek secara massal dan melakukannya di latar belakang.

Untuk mempelajari cara mendapatkan informasi error mendetail tentang operasi Cloud Storage yang gagal di Google Cloud konsol, lihat Pemecahan masalah.

Command line

Google Cloud CLI

Untuk menghapus grup objek dengan imbuhan yang sama, seperti objek yang namanya meniru struktur folder, gunakan flag --recursive dengan gcloud storage rm:

gcloud storage rm --recursive gs://BUCKET_NAME/PREFIX

Dengan:

  • BUCKET_NAME adalah nama bucket. Contoh, my-bucket.
  • PREFIX adalah awalan umum objek yang ingin Anda hapus. Contoh, pets/.

CLI Amazon S3

Untuk menghapus beberapa objek di Cloud Storage menggunakan Amazon S3 CLI, gunakan perintah aws s3api delete-objects. Anda harus mengalihkan permintaan ke multi-object delete XML API Cloud Storage dengan menetapkan tanda --endpoint-url ke storage.googleapis.com. Untuk mengetahui definisi parameter dan perilaku API delete-objects secara mendetail, lihat dokumentasi referensi delete-objects CLI Amazon S3.

Library klien

Cloud Storage mendukung XML API penghapusan multi-objek melalui antarmuka yang kompatibel dengan Amazon S3. Untuk menggunakan library klien yang kompatibel dengan Amazon S3 untuk penghapusan objek massal, arahkan permintaan Anda ke endpoint Google Cloud dengan menyetel URL endpoint ke https://storage.googleapis.com dalam konfigurasi klien. Pendekatan ini dapat bermanfaat jika Anda melakukan salah satu tugas berikut:

  • Memanfaatkan codebase atau alat yang sudah ada yang dibuat untuk Amazon S3.
  • Mempertahankan konsistensi di seluruh lingkungan multi-cloud yang mencakup Amazon S3 dan Cloud Storage.

Contoh berikut menunjukkan cara menginisialisasi klien menggunakan library Boto3 untuk berinteraksi dengan Cloud Storage:

  import boto3
  def main():
  # Initialize the S3 client to point to the Google Cloud Storage endpoint
    client = boto3.client(
        service_name='s3',
        endpoint_url='https://storage.googleapis.com',
        aws_access_key_id='YOUR_ACCESS_ID',
        aws_secret_access_key='YOUR_SECRET',
    )
  # Perform delete operations as defined in the library's documentation
  # response = client.delete_objects(Bucket='BUCKET_NAME', Delete={'Objects': [...]})
  

Untuk mengetahui tanda tangan metode dan definisi parameter tertentu, lihat dokumentasi delete_objects Boto3.

XML API

Untuk menghapus hingga 1.000 objek dalam satu permintaan menggunakan XML API, selesaikan langkah-langkah berikut:

  1. Instal dan lakukan inisialisasigcloud CLI, yang memungkinkan Anda membuat token akses untuk header Authorization.

  2. Buat dokumen XML yang menentukan objek yang akan dihapus.

    Untuk mengetahui daftar lengkap setelan, lihat Menghapus beberapa objek dalam dokumentasi referensi XML API. Setelan umum yang harus disertakan dalam file XML Anda adalah sebagai berikut:

    <Delete>
        <Object>
          <Key>OBJECT_NAME</Key>
          <VersionId>VERSION_ID</VersionId>
        </Object>
        ...
        <Quiet>QUIET_RESPONSE_BOOLEAN</Quiet>
      </Delete>

    Dengan:

    • OBJECT_NAME adalah nama objek yang dienkode ke URL. Contoh, pets/dog.png, URL dienkode sebagai pets%2Fdog.png. Anda dapat menentukan hingga 1.000 objek dalam file XML.
    • VERSION_ID adalah ID versi untuk objek. Misalnya, 11111.
    • QUIET_RESPONSE_BOOLEAN mengontrol kejelasan respons API:
      • Setel ke False untuk respons verbose. Respons menyertakan detail untuk setiap objek, baik yang berhasil dihapus maupun tidak. Operasi penghapusan multi-objek menggunakan XML API tidak bersifat atomik. Jika permintaan menghasilkan kegagalan sebagian, beberapa objek mungkin berhasil dihapus, tetapi objek lainnya mungkin gagal dihapus. Jadi, sebaiknya gunakan respons verbose untuk mengidentifikasi semua penghapusan objek. Jika log audit Akses Data diaktifkan, Anda juga dapat meninjau log audit untuk mengetahui detail kegagalan.
      • Setel ke True untuk respons yang tenang. Isi respons tidak menyertakan informasi tentang objek yang berhasil dihapus.
  3. Gunakan curl untuk mengirim permintaan bucket POST ke XML API dengan parameter kueri ?delete dan file XML Anda:

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

    Dengan:

    • XML_FILE_NAME adalah nama file XML yang Anda buat.
    • BUCKET_NAME adalah nama bucket yang berisi objek yang akan dihapus.

      Jika mode Quiet dinonaktifkan, respons verbose mungkin terlihat seperti berikut:

      <DeleteResult>
      <Deleted>
        <Key>images/photo1.jpg</Key>
        <VersionId>11111</VersionId>
      </Deleted>
      <Deleted>
        <Key>documents/report.pdf</Key>
        <VersionId>22222</VersionId>
      </Deleted>
      <Error>
        <Code>AccessDenied</Code>
        <Key>private/financial_data.xlsx</Key>
        <Message>Access Denied. You don't have permission to delete this object.</Message>
        <VersionId>33333</VersionId>
      </Error>
      </DeleteResult>
      

      Jika mode Quiet diaktifkan, respons hanya mencantumkan objek yang gagal dihapus. Jika semua objek berhasil dihapus, tag <DeleteResult/> kosong akan ditampilkan. Berikut adalah contoh respons senyap saat terjadi error:

      <DeleteResult>
      <Error>
        <Code>AccessDenied</Code>
        <Key>private/financial_data.xlsx</Key>
        <Message>Access Denied. You don't have permission to delete this object.</Message>
        <VersionId>33333</VersionId>
      </Error>
      </DeleteResult>

Menghapus hingga miliaran objek

Untuk menghapus jutaan atau miliaran objek dengan satu tugas penghapusan objek, gunakan operasi batch penyimpanan. Untuk membuat tugas, tentukan objek yang akan dihapus, baik dengan memberikan daftar objek dalam file manifes atau menggunakan prefiks objek. Setelah Anda menentukan daftar objek, buat tugas operasi batch untuk menghapus objek.

Menghapus objek secara otomatis menggunakan aturan siklus proses objek

Jika Anda ingin objek dihapus secara otomatis saat memenuhi kriteria yang Anda tentukan, seperti usia atau kelas penyimpanan, gunakan Object Lifecycle Management. Misalnya, Anda dapat menetapkan aturan siklus proses untuk menghapus log yang lebih lama dari 30 hari.

Membuat batch permintaan penghapusan objek dengan JSON API

Untuk mengurangi jumlah koneksi HTTP yang diperlukan saat menghapus banyak objek dengan JSON API, gunakan permintaan batch JSON API. Anda dapat mengelompokkan hingga 100 panggilan API ke dalam satu permintaan HTTP untuk membantu mengurangi overhead jaringan.

Langkah berikutnya