Delete objectsStay organized with collectionsSave and categorize content based on your preferences.
This page shows you how to deleteobjectsfrom your buckets in
Cloud Storage. For an overview of object deletion methods, seeAbout object deletion.
Required roles
To get the permissions that
you need to delete objects,
ask your administrator to grant you the
following IAM roles on the bucket that contains the objects you want to delete:
Delete objects using Google Cloud CLI or REST APIs:Storage Object User(roles/storage.objectUser)
Delete objects using the Google Cloud console:Storage Admin(roles/storage.admin)
Alternatively, to delete objects using the Google Cloud console:
Viewer (roles/viewer) and Storage Object User (roles/storage.objectUser)
These predefined roles contain
the permissions required to delete objects. To see the exact permissions that are
required, expand theRequired permissionssection:
Required permissions
The following permissions are required to delete objects:
Delete objects:storage.objects.delete
List objects using the Google Cloud console, or using the--recursiveflag or wildcards in Google Cloud CLI:storage.objects.list
List buckets using the Google Cloud console:storage.buckets.list
namespacegcs=::google::cloud::storage;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name){google::cloud::Statusstatus=client.DeleteObject(bucket_name,object_name);if(!status.ok())throwstd::runtime_error(status.message());std::cout<<"Deleted "<<object_name<<" in bucket "<<bucket_name<<"\n";}
import("context""fmt""io""time""cloud.google.com/go/storage")// deleteFile removes specified object.funcdeleteFile(wio.Writer,bucket,objectstring)error{// bucket := "bucket-name"// object := "object-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()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)iferr!=nil{returnfmt.Errorf("object.Attrs: %w",err)}o=o.If(storage.Conditions{GenerationMatch:attrs.Generation})iferr:=o.Delete(ctx);err!=nil{returnfmt.Errorf("Object(%q).Delete: %w",object,err)}fmt.Fprintf(w,"Blob %v deleted.\n",object)returnnil}
importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassDeleteObject{publicstaticvoiddeleteObject(StringprojectId,StringbucketName,StringobjectName){// 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";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Blobblob=storage.get(bucketName,objectName);if(blob==null){System.out.println("The object "+objectName+" wasn't found in "+bucketName);return;}BlobIdidWithGeneration=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);}}
/*** 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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();// 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.constdeleteOptions={ifGenerationMatch:generationMatchPrecondition,};asyncfunctiondeleteFile(){awaitstorage.bucket(bucketName).file(fileName).delete(deleteOptions);console.log(`gs://${bucketName}/${fileName}deleted`);}deleteFile().catch(console.error);
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);}
fromgoogle.cloudimportstoragedefdelete_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.generationblob.delete(if_generation_match=generation_match_precondition)print(f"Blob{blob_name}deleted.")
defdelete_filebucket_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.newbucket=storage.bucketbucket_name,skip_lookup:truefile=bucket.filefile_namefile.deleteputs"Deleted#{file.name}"end
Rust
usegoogle_cloud_storage::client::StorageControl;pubasyncfnsample(client:&StorageControl,bucket_id:&str)->anyhow::Result<()>{constNAME:&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(())}
BUCKET_NAMEis the name of the bucket
containing the object you want to delete. For example,my-bucket.
OBJECT_NAMEis the URL-encoded name of
the object you want to delete. For example,pets/dog.png,
URL-encoded aspets%2Fdog.png.
Delete objects in bulk
This section shows how to delete objects in bulk by selecting them in the
Google Cloud console, by deleting objects with a common prefix using
command-line tools, or by specifying a list of objects in API or client
library requests.
Console
In the Google Cloud console, go to the Cloud StorageBucketspage.
In the list of buckets, click the name of the bucket that contains
the objects you want to delete.
TheBucket detailspage opens, with theObjectstab selected.
Navigate to the objects, which may be located in a folder.
Select the checkbox for each object you want to delete.
You can select the checkbox for a folder, which deletes all
objects contained in that folder.
ClickDelete, and then clickDeletein the dialog that appears.
If you delete many objects at once, you can track deletion progress by
clicking theNotificationsicon in the Google Cloud console. The
Google Cloud console can bulk delete up to several million objects
and does so in the background.
To learn how to get detailed error information about failed Cloud Storage
operations in the Google Cloud console, seeTroubleshooting.
BUCKET_NAMEis the name of the bucket. For example,my-bucket.
PREFIXis common prefix of the objects you want to delete. For example,pets/.
Amazon S3 CLI
To delete multiple objects in Cloud Storage using the Amazon S3
CLI, use theaws s3api delete-objectscommand. You'll need to redirect the
request to the Cloud Storagemulti-object delete XML APIby
setting the--endpoint-urlflag tostorage.googleapis.com. For detailed parameter
definitions and behavior ofdelete-objectsAPI, see theAmazon S3 CLI
delete-objects reference documentation.
Client libraries
Cloud Storage supports themulti-object delete XML APIthrough its Amazon S3-compatible interface.
To use Amazon S3-compatible client libraries for bulk object deletion, point
your request to the Google Cloud endpoint by setting the endpoint URL tohttps://storage.googleapis.comin the client configuration. This approach can be beneficial if you are performing any of the following tasks:
Leveraging existing codebases or tooling already built for Amazon S3.
Maintaining consistency across multi-cloud environments that include both Amazon S3 and Cloud Storage.
The following example shows how to initialize a client using aBoto3library to interact with 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': [...]})
Create an XML document that specifies the objects to be deleted.
For a complete list of settings, seeDelete multiple objectsin the XML API reference documentation.
The common settings to include in your XML file are as follows:
OBJECT_NAMEis the URL-encoded name of the object. For example,pets/dog.png, URL-encoded aspets%2Fdog.png. You can specify up to 1,000 objects in the XML file.
VERSION_IDis theversion IDfor the object. For example,11111.
QUIET_RESPONSE_BOOLEANcontrols the verbosity of the API's response:
Set toFalsefor a verbose response. The response includes details for every object, whether it is successfully deleted or not. The multi-object delete operation using the XML API is not atomic. If a request results in partial failures, some objects might be successfully deleted but other objects might fail to be deleted, so we recommend using the verbose response to identify all object deletions. If you haveData Access audit logs enabled, you can also review audit logs for failure details.
Set toTruefor a quiet response. The response body doesn't include information about the objects that are successfully deleted.
Usecurlto send aPOSTbucketrequest to theXML APIwith the?deletequery parameter and your XML file:
XML_FILE_NAMEis the name of the XML file you created.
BUCKET_NAMEis the name of the bucket containing the objects to delete.
IfQuietmode is disabled, a verbose response might look similar to the following:
<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>
IfQuietmode is enabled, the response lists only objects that
failed to delete. If all objects are successfully deleted, an empty<DeleteResult/>tag is returned. The following is
an example of a quiet response where an error occurred:
To delete millions or billions of objects with a single object deletion job, usestorage batch operations. To create a job, specify the objects to delete,
either by providing a list of objects in a manifest file or by using object
prefixes. After you have specified the object list,create a batch operation job to
delete the objects.
Automatically delete objects using object lifecycle rules
If you want objects to be deleted automatically when they meet criteria that
you specify, such as age or storage class, useObject Lifecycle Management. For example, you can set a lifecycle rule
to delete logs that are older than 30 days.
Batch object deletion requests with JSON API
To reduce the number of HTTP connections needed when deleting many objects
with the JSON API, useJSON API batch requests. You can
group up to 100 API calls into a single HTTP request to help reduce network
overhead.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-04-09 UTC."],[],[]]