מחיקת אובייקטים

בדף הזה מוסבר איך למחוק אובייקטים מקטגוריות ב-Cloud Storage.

התפקידים הנדרשים

כדי לקבל את ההרשאות שנדרשות למחיקת אובייקטים, צריך לבקש מהאדמין להקצות לכם את תפקיד ה-IAM 'משתמש באובייקט אחסון' (roles/storage.objectUser) בקטגוריה שמכילה את האובייקטים שאתם רוצים למחוק.

אם אתם מתכננים להשתמש במסוף Google Cloud כדי לבצע את המשימות שמופיעות בדף הזה, בקשו מהאדמין להקצות לכם את התפקיד 'אדמין לניהול אחסון' (roles/storage.admin) במקום התפקיד 'משתמש באובייקט אחסון' (roles/storage.objectUser), או את התפקיד הבסיסי 'צפייה' (roles/viewer) בנוסף לתפקיד 'משתמש באובייקט אחסון' (roles/storage.objectUser).

התפקידים האלה כוללים את ההרשאות שנדרשות למחיקת אובייקטים. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:

ההרשאות הנדרשות

  • storage.objects.delete
  • storage.objects.list
    • ההרשאה הזו נדרשת רק כשמשתמשים במסוף Google Cloud , או כשמשתמשים בדגל --recursive או בתווים כלליים ב-Google Cloud CLI.
  • storage.buckets.list
    • ההרשאה הזו נדרשת רק כשמשתמשים במסוף Google Cloud כדי לבצע את ההוראות שבדף הזה.

אפשר לקבל את ההרשאות האלה גם באמצעות תפקידים מוגדרים מראש אחרים או תפקידים בהתאמה אישית.

במאמר הגדרה וניהול של מדיניות IAM בקטגוריות מוסבר איך מקצים תפקידים בקטגוריות.

מחיקת אובייקט

כדי למחוק אובייקטים מאחת מהקטגוריות של Cloud Storage, מבצעים את הפעולות הבאות:

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, לוחצים על שם הקטגוריה שמכילה את האובייקטים שרוצים למחוק.

    הדף Bucket details נפתח עם הכרטיסייה Objects שנבחרה.

  3. עוברים אל האובייקטים, שאולי יהיו ממוקמים בתיקייה.

  4. לוחצים על תיבת הסימון לצד כל אובייקט שרוצים למחוק.

    אפשר גם לסמן את התיבה של התיקיות, ובעקבות זאת יימחקו כל האובייקטים שבתיקייה הזו.

  5. לוחצים על הלחצן Delete.

  6. לוחצים על Delete בתיבת הדו-שיח שמופיעה.

אם מוחקים מספר אובייקטים בבת אחת, אפשר ללחוץ על הסמל Notifications במסוף 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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

/**
 * 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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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(())
}

ממשקי API ל-REST

‫API בפורמט JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשת DELETE:

    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/dog.png יותאם לקידודי התווים שמתאימים לכתובות URL באופן הבא: pets%2Fdog.png.

‫API בפורמט XML

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט XML באמצעות בקשת DELETE Object:

    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/dog.png יותאם לקידודי התווים שמתאימים לכתובות URL באופן הבא: pets%2Fdog.png.

מחיקת כמות גדולה של אובייקטים

אם רוצים למחוק כמות גדולה של מאה אלף אובייקטים או יותר, כדאי להימנע משימוש ב-gcloud storage, כי התהליך נמשך הרבה זמן. במקום זאת, כדאי לשקול אחת מהאפשרויות הבאות:

  • התכונה ניהול מחזור חיים של אובייקטים יכולה למחוק כל מספר של אובייקטים. כדי למחוק אובייקטים בקטגוריה בכמות גדולה באמצעות התכונה הזו, צריך להגדיר כלל למחזור החיים בקטגוריה, כאשר תנאי הערך של Age מוגדר ל-0 ימים והפעולה מוגדרת ל-delete. אחרי שמגדירים את הכלל, Cloud Storage מבצע את המחיקה בכמות גדולה באופן אסינכרוני.

  • מומלץ להשתמש במסוף Google Cloud גם כשרוצים למחוק עד מיליון אובייקטים. אחרי ששולחים בקשת מחיקה כזו, התהליך מתבצע ברקע. כדי לבדוק את הסטטוס של המחיקה בכמות גדולה, לוחצים על הלחצן Notifications () בכותרת של מסוף Google Cloud .

  • כשמשתמשים בספריות לקוח מסוימות או כשמשתמשים ישירות ב-API בפורמט JSON, אפשר לקבץ את בקשות המחיקה כדי לצמצם את מספר חיבורי ה-HTTP שצריך לבצע.

המאמרים הבאים