객체 삭제하기

이 페이지는 Cloud Storage의 버킷에서 객체를 삭제하는 방법을 설명합니다.

시작하기 전에

객체를 삭제하는 데 필요한 권한을 얻으려면 관리자에게 삭제할 객체가 포함된 버킷에 대한 스토리지 객체 사용자(roles/storage.objectUser) IAM 역할을 부여해달라고 요청하세요.

Google Cloud 콘솔을 사용하여 이 페이지의 태스크를 완료하려면 관리자에게 스토리지 객체 사용자(roles/storage.objectUser) 역할 대신 스토리지 관리자(roles/storage.admin) 역할을 부여하거나 스토리지 객체 사용자(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 콘솔은 최대 수백만 개의 객체를 일괄 삭제할 수 있으며 삭제 작업은 백그라운드에서 수행됩니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

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.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;
    }

    // Optional: set a generation-match precondition to avoid potential race
    // conditions and data corruptions. The request to upload returns a 412 error if
    // the object's generation number does not match your precondition.
    Storage.BlobSourceOption precondition =
        Storage.BlobSourceOption.generationMatch(blob.getGeneration());

    storage.delete(bucketName, objectName, precondition);

    System.out.println("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';

// 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. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 DELETE 요청으로 JSON API를 호출합니다.

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

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰의 이름입니다.
    • BUCKET_NAME은 삭제할 객체가 포함된 버킷의 이름입니다. 예: my-bucket
    • OBJECT_NAME은 삭제할 객체의 URL 인코딩 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.

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"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰의 이름입니다.
    • BUCKET_NAME은 삭제할 객체가 포함된 버킷의 이름입니다. 예: my-bucket
    • OBJECT_NAME은 삭제할 객체의 URL 인코딩 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.

객체 일괄 삭제

수십만 개 이상의 객체를 일괄 삭제하려면 프로세스 완료에 시간이 오래 걸리는 gcloud storage을 사용하지 않는 것이 좋습니다. 대신 다음 옵션 중 하나를 고려해 보세요.

  • 객체 수명 주기 관리 기능은 객체 수를 원하는 만큼 삭제할 수 있습니다. 이 기능을 사용하여 버킷의 객체를 일괄 삭제하려면 조건에서 Age가 0일로 설정되고 작업이 delete로 설정된 버킷에서 수명 주기 구성 규칙을 설정합니다. 이 규칙을 설정하면 Cloud Storage에서 일괄 삭제를 비동기적으로 수행합니다.

  • 객체를 최대 100만 개 삭제하는 경우 Google Cloud 콘솔도 권장되는 옵션입니다. 이러한 삭제 요청을 시작하면 프로세스가 백그라운드에서 수행됩니다. Google Cloud 콘솔 헤더에서 알림 버튼()을 클릭하여 일괄 삭제 상태를 확인할 수 있습니다.

  • 특정 클라이언트 라이브러리를 사용하거나 JSON API를 직접 사용하는 경우 삭제 요청을 배치하여 필요한 HTTP 연결 수를 줄일 수 있습니다.

다음 단계