Use versioned objects Stay organized with collections Save and categorize content based on your preferences.
This page describes how to list, access, restore, and delete noncurrent objects,which typically applies to buckets withObject Versioning enabled.Noncurrent objects are also referred to as versioned objects.
Before you begin
To work with noncurrent objects, complete the following prerequisite steps.
Enable Object Versioning
If you haven't already,enable Object Versioning on your bucket.
Get required roles
To get the permissions that you need to manage noncurrent objects, ask youradministrator to grant you the Storage Object User (roles/storage.objectUser)IAM role on the project. Thispredefined role contains thepermissions required to manage noncurrent objects. To see the exactpermissions that are required, expand theRequired permissions section:
Required permissions
storage.objects.createstorage.objects.deletestorage.objects.getstorage.objects.list
You might also be able to get these permissions withcustom roles.
For information about granting roles on projects, seeManage access to projects.
Depending on your use case, you might need additional permissions or alternativeroles:
If you plan on using the Google Cloud console to perform the tasks on thispage, you'll also need the
storage.buckets.listpermission, which is notincluded in the Storage Object User (roles/storage.objectUser) role.To get this permission, ask your administrator to grant you the Storage Admin(roles/storage.admin) role on the project.If uniform bucket-level access is disabled for your bucket, you need additionalpermissions in the following scenarios:
If you plan on returning noncurrent objects along with their ACLs, youalso need the
storage.objects.getIamPolicypermission, which is notincluded in the Storage Object User (roles/storage.objectUser) role.To get this permission, ask your administrator to grant you the StorageObject Admin (roles/storage.objectAdmin) role on the project.If you plan on renaming or restoring noncurrent objects that have ACLs,you also need the
storage.objects.setIamPolicypermission, which is notincluded in the Storage Object User (roles/storage.objectUser) role.To get this permission, ask your administrator to grant you the StorageObject Admin (roles/storage.objectAdmin) role on the project.
List noncurrent object versions
To list both live and noncurrent versions of objects and view theirgeneration numbers:
Console
Note: The Google Cloud console has a limit of 1000 versions of an objectthat it can list. To see more versions for an object, use thegcloud CLI.- In the Google Cloud console, go to the Cloud StorageBuckets page.
In the list of buckets, click the name of the bucket that containsthe wanted object.
TheBucket details page opens, with theObjects tab selected.
To view noncurrent objects, click theShow drop-down and selectLive and noncurrent objects.
In the list of objects, click the name of the object whose versionsyou want to see.
TheObject details page opens, with theLive Object tabselected.
Click theVersion history tab to see all versions of the object.
Command line
Use thegcloud storage ls --all-versions command:
gcloud storage ls --all-versions gs://BUCKET_NAME
WhereBUCKET_NAME is the name of the bucket thatcontains the objects. For example,my-bucket.
The response looks like the following example:
gs://BUCKET_NAME/OBJECT_NAME1#GENERATION_NUMBER1gs://BUCKET_NAME/OBJECT_NAME2#GENERATION_NUMBER2gs://BUCKET_NAME/OBJECT_NAME3#GENERATION_NUMBER3...
--long flag along with the--all-versions flag to getmetageneration numbers in the response. Use the--full flag along withthe--all-versions flag to get theNoncurrent Time for noncurrentversions of an object.Client libraries
For more information, see theCloud StorageC++ API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageC# API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageGo API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageJava API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageNode.js API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StoragePHP API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StoragePython API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageRuby API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.C++
namespacegcs=::google::cloud::storage;[](gcs::Clientclient,std::stringconst&bucket_name){for(auto&&object_metadata:client.ListObjects(bucket_name,gcs::Versions{true})){if(!object_metadata)throwstd::move(object_metadata).status();std::cout <<"bucket_name=" <<object_metadata->bucket() <<", object_name=" <<object_metadata->name() <<", generation=" <<object_metadata->generation() <<"\n";}}C#
usingGoogle.Cloud.Storage.V1;usingSystem;usingSystem.Collections.Generic;publicclassListFileArchivedGenerationSample{publicIEnumerable<Google.Apis.Storage.v1.Data.Object>ListFileArchivedGeneration(stringbucketName="your-bucket-name"){varstorage=StorageClient.Create();varstorageObjects=storage.ListObjects(bucketName,options:newListObjectsOptions{Versions=true});foreach(varstorageObjectinstorageObjects){Console.WriteLine($"Filename: {storageObject.Name}, Generation: {storageObject.Generation}");}returnstorageObjects;}}Go
import("context""fmt""io""time""cloud.google.com/go/storage""google.golang.org/api/iterator")// listFilesAllVersion lists both live and noncurrent versions of objects within specified bucket.funclistFilesAllVersion(wio.Writer,bucketstring)error{// bucket := "bucket-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()it:=client.Bucket(bucket).Objects(ctx,&storage.Query{// Versions true to output all generations of objectsVersions:true,})for{attrs,err:=it.Next()iferr==iterator.Done{break}iferr!=nil{returnfmt.Errorf("Bucket(%q).Objects(): %w",bucket,err)}fmt.Fprintln(w,attrs.Name,attrs.Generation,attrs.Metageneration)}returnnil}Java
importcom.google.api.gax.paging.Page;importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassListObjectsWithOldVersions{publicstaticvoidlistObjectsWithOldVersions(StringprojectId,StringbucketName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Bucketbucket=storage.get(bucketName);Page<Blob>blobs=bucket.list(Storage.BlobListOption.versions(true));for(Blobblob:blobs.iterateAll()){System.out.println(blob.getName()+","+blob.getGeneration());}}}Node.js
/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionlistFilesWithOldVersions(){const[files]=awaitstorage.bucket(bucketName).getFiles({versions:true,});console.log('Files:');files.forEach(file=>{console.log(file.name,file.generation);});}listFilesWithOldVersions().catch(console.error);PHP
use Google\Cloud\Storage\StorageClient;/** * List objects in a specified bucket with all archived generations. * * @param string $bucketName The name of your Cloud Storage bucket. * (e.g. 'my-bucket') */function list_file_archived_generations(string $bucketName): void{ $storage = new StorageClient(); $bucket = $storage->bucket($bucketName); $objects = $bucket->objects([ 'versions' => true, ]); foreach ($objects as $object) { print($object->name() . ',' . $object->info()['generation'] . PHP_EOL); }}Python
fromgoogle.cloudimportstoragedeflist_file_archived_generations(bucket_name):"""Lists all the blobs in the bucket with generation."""# bucket_name = "your-bucket-name"storage_client=storage.Client()blobs=storage_client.list_blobs(bucket_name,versions=True)forblobinblobs:print(f"{blob.name},{blob.generation}")Ruby
REST APIs
JSON API
Have gcloud CLIinstalled and initialized, which lets you generate an access token for the
Authorizationheader.Use
cURLto call theJSON API with anObjects: list request:curl -X GET \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o?versions=true"
Where
BUCKET_NAMEis the name of thebucket that contains the objects. For example,my-bucket.
Noncurrent versions of objects have atimeDeleted property.
XML API
Have gcloud CLIinstalled and initialized, which lets you generate an access token for the
Authorizationheader.Use
cURLto call theXML API, with aGETBucket request andversionsquery string parameter:curl -X GET \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/BUCKET_NAME?versions&list-type=2"
Where
BUCKET_NAMEis the name of thebucket that contains the objects. For example,my-bucket.
There are a few differences in the results of theGET request whenusing theversions query parameter compared to not using it.Specifically, Cloud Storage returns the following information whenyou include aversions query parameter in your request:
- A
Versionelement that contains information about each object. - A
DeletedTimeelement that contains the time the object versionbecame noncurrent (deleted or replaced). - An `IsLatest element that indicates if the specific object is thelatest version.
- A
NextGenerationMarkerelement is returned if the listing of objectsis a partial listing, which occurs when you have many objectversions in a bucket. Use the value of this element in thegenerationmarkerquery parameter of subsequent requests in orderto resume from your last point. Thegenerationmarkerqueryparameter is used in the same way that you use themarkerqueryparameter to page through a listing for a nonversioned bucket.
Access noncurrent object versions
To use the noncurrent version of an object when performing tasks such asdownloading the object, viewing its metadata, or updating its metadata:
Console
General access to a noncurrent version is not available in theGoogle Cloud console. Using the Google Cloud console, you can only move,copy,restore ordelete a noncurrent version. These actionsare performed from theversion history list for an object.
Command line
Append thegeneration number of the noncurrent version to theobject name:
OBJECT_NAME#GENERATION_NUMBER
Where:
OBJECT_NAMEis the name of the noncurrentversion. For example,pets/dog.png.GENERATION_NUMBERis the generation numberfor the noncurrent version. For example,1560468815691234.
Using the string from the previous step, proceed as you normally wouldfor the live version of the object. For example, to view the metadata ofa noncurrent object version, use the
gcloud storage objects describecommand:gcloud storage objects describe gs://my-bucket/pets/dog.png#1560468815691234
REST APIs
JSON API
Append thegeneration number of the noncurrent version to theURI for the object:
https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?generation=GENERATION_NUMBER
Where:
BUCKET_NAMEis the name of the bucketcontaining the noncurrent version. For example,my-bucket.OBJECT_NAMEis the URL-encoded name of thenoncurrent version. For example,pets/dog.png, URL-encoded aspets%2Fdog.png.GENERATION_NUMBERis the generation numberfor the noncurrent version. For example,1560468815691234.
Using the URI from the previous step, proceed as you normally wouldfor the live version of the object. For example, to view the metadataof a noncurrent object version, usecURL to call theJSON API with anObjects: get request:
curl -X GET \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/storage/v1/b/my-bucket/o/pets/dog.png?generation=1560468815691234"
XML API
Append thegeneration number of the noncurrent version to theURI for the object:
https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME?generation=GENERATION_NUMBER
Where:
BUCKET_NAMEis the name of the bucketcontaining the noncurrent version. For example,my-bucket.OBJECT_NAMEis the URL-encoded name of thenoncurrent version. For example,pets/dog.png, URL-encoded aspets%2Fdog.png.GENERATION_NUMBERis the generationnumber for the noncurrent version. For example,1560468815691234.
Using the URI from the previous step, proceed as you normally wouldfor the live version of the object. For example, to view the metadataof a noncurrent object version, use
cURLto call theXML API with aHEADObject request:curl -I GET \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/my-bucket/pets/dog.png?generation=1560468815691234"
Restore noncurrent object versions
In Cloud Storage, restoring a noncurrent object version means making acopy of it. When you do so, the copy becomes the live version, effectivelyrestoring the version. If there is already a live version and the bucket hasObject Versioning enabled, restoring the noncurrent version causes thepre-existing live version to become noncurrent.
Console
Note: The Google Cloud console has a limit of 1000 versions of an objectthat it can list.- In the Google Cloud console, go to the Cloud StorageBuckets page.
In the list of buckets, click the name of the bucket that containsthe wanted object.
TheBucket details page opens, with theObjects tab selected.
To view noncurrent objects, click theShow drop-down and selectLive and noncurrent objects.
In the list of objects, click the name of the object version you want torestore.
TheObject details page opens, with theLive Object tabselected.
Click theVersion history tab.
Click theRestore button for the wanted version.
The restore object version pane opens.
ClickConfirm.
Command line
Use thegcloud storage cp command:
gcloud storage cp gs://BUCKET_NAME/OBJECT_NAME#GENERATION_NUMBER gs://BUCKET_NAME
Where:
BUCKET_NAMEis the name of the bucketcontaining the noncurrent version you want to restore. For example,my-bucket.OBJECT_NAMEis the name of the noncurrentversion you want to restore. For example,pets/dog.png.GENERATION_NUMBERis thegeneration numberfor the noncurrent version you want to restore. For example,1560468815691234.
If successful, the response looks like the following example:
Operation completed over 1 objects/58.8 KiB.
extendedglob option isenabled, treat the hash character,#, as a special character. If thisis the case for your shell, you should enclose that argument in singlequotes (or double quotes for Windows).Client libraries
For more information, see theCloud StorageC++ API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageC# API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageGo API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageJava API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageNode.js API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StoragePHP API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StoragePython API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageRuby API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.C++
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&source_bucket_name,std::stringconst&source_object_name,std::stringconst&destination_bucket_name,std::stringconst&destination_object_name,std::int64_tsource_object_generation){StatusOr<gcs::ObjectMetadata>copy=client.CopyObject(source_bucket_name,source_object_name,destination_bucket_name,destination_object_name,gcs::SourceGeneration{source_object_generation});if(!copy)throwstd::move(copy).status();std::cout <<"Successfully copied " <<source_object_name <<" generation " <<source_object_generation <<" in bucket " <<source_bucket_name <<" to bucket " <<copy->bucket() <<" with name " <<copy->name() <<".\nThe full metadata after the copy is: " <<*copy <<"\n";}C#
usingGoogle.Cloud.Storage.V1;usingSystem;publicclassCopyFileArchivedGenerationSample{publicGoogle.Apis.Storage.v1.Data.ObjectCopyFileArchivedGeneration(stringsourceBucketName="source-bucket-name",stringsourceObjectName="source-file",stringdestBucketName="destination-bucket-name",stringdestObjectName="destination-file-name",long?generation=1579287380533984){varstorage=StorageClient.Create();varcopyOptions=newCopyObjectOptions{SourceGeneration=generation};varcopiedFile=storage.CopyObject(sourceBucketName,sourceObjectName,destBucketName,destObjectName,copyOptions);Console.WriteLine($"Generation {generation} of the object {sourceBucketName}/{sourceObjectName} "+$"was copied to to {destBucketName}/{destObjectName}.");returncopiedFile;}}Go
import("context""fmt""io""time""cloud.google.com/go/storage")// copyOldVersionOfObject copies a noncurrent version of an object.funccopyOldVersionOfObject(wio.Writer,bucket,srcObject,dstObjectstring,genint64)error{// bucket := "bucket-name"// srcObject := "source-object-name"// dstObject := "destination-object-name"// gen is the generation of srcObject to copy.// gen := 1587012235914578ctx:=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()src:=client.Bucket(bucket).Object(srcObject)dst:=client.Bucket(bucket).Object(dstObject)// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request to copy is aborted if the// object's generation number does not match your precondition.// For a dst object that does not yet exist, set the DoesNotExist precondition.dst=dst.If(storage.Conditions{DoesNotExist:true})// If the destination object already exists in your bucket, set instead a// generation-match precondition using its generation number.// attrs, err := dst.Attrs(ctx)// if err != nil {// return fmt.Errorf("object.Attrs: %w", err)// }// dst = dst.If(storage.Conditions{GenerationMatch: attrs.Generation})if_,err:=dst.CopierFrom(src.Generation(gen)).Run(ctx);err!=nil{returnfmt.Errorf("Object(%q).CopierFrom(%q).Generation(%v).Run: %w",dstObject,srcObject,gen,err)}fmt.Fprintf(w,"Generation %v of object %v in bucket %v was copied to %v\n",gen,srcObject,bucket,dstObject)returnnil}Java
importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassCopyOldVersionOfObject{publicstaticvoidcopyOldVersionOfObject(StringprojectId,StringbucketName,StringobjectToCopy,longgenerationToCopy,StringnewObjectName){// 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 the GCS object to copy an old version of// String objectToCopy = "your-object-name";// The generation of objectToCopy to copy// long generationToCopy = 1579287380533984;// What to name the new object with the old data from objectToCopy// String newObjectName = "your-new-object";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request returns a 412 error if the// preconditions are not met.Storage.BlobTargetOptionprecondition;if(storage.get(bucketName,newObjectName)==null){// For a target object that does not yet exist, set the DoesNotExist precondition.// This will cause the request to fail if the object is created before the request runs.precondition=Storage.BlobTargetOption.doesNotExist();}else{// If the destination already exists in your bucket, instead set a generation-match// precondition. This will cause the request to fail if the existing object's generation// changes before the request runs.precondition=Storage.BlobTargetOption.generationMatch(storage.get(bucketName,newObjectName).getGeneration());}Storage.CopyRequestcopyRequest=Storage.CopyRequest.newBuilder().setSource(BlobId.of(bucketName,objectToCopy,generationToCopy)).setTarget(BlobId.of(bucketName,newObjectName),precondition).build();storage.copy(copyRequest);System.out.println("Generation "+generationToCopy+" of object "+objectToCopy+" in bucket "+bucketName+" was copied to "+newObjectName);}}Node.js
/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const srcBucketName = "your-unique-bucket-name";// The ID of the GCS file to copy an old version of// const srcFilename = "your-file-name";// The generation of fileToCopy to copy// const generation = 1579287380533984;// The ID of the bucket to copy the file to// const destBucketName = 'target-file-bucket';// What to name the new file with the old data from srcFilename// const destFileName = "your-new-file";// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctioncopyOldVersionOfFile(){// Copies the file to the other bucket// Optional:// Set a generation-match precondition to avoid potential race conditions// and data corruptions. The request to copy 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.constcopyOptions={preconditionOpts:{ifGenerationMatch:destinationGenerationMatchPrecondition,},};awaitstorage.bucket(srcBucketName).file(srcFilename,{generation,}).copy(storage.bucket(destBucketName).file(destFileName),copyOptions);console.log(`Generation${generation} of file${srcFilename} in bucket${srcBucketName} was copied to${destFileName} in bucket${destBucketName}`);}copyOldVersionOfFile().catch(console.error);PHP
use Google\Cloud\Storage\StorageClient;/** * Copy archived generation of a given object to a new object. * * @param string $bucketName The name of your Cloud Storage bucket. * (e.g. 'my-bucket') * @param string $objectToCopy The name of the object to copy. * (e.g. 'my-object') * @param string $generationToCopy The generation of the object to copy. * (e.g. 1579287380533984) * @param string $newObjectName The name of the target object. * (e.g. 'my-object-1579287380533984') */function copy_file_archived_generation(string $bucketName, string $objectToCopy, string $generationToCopy, string $newObjectName): void{ $storage = new StorageClient(); $bucket = $storage->bucket($bucketName); $object = $bucket->object($objectToCopy, [ 'generation' => $generationToCopy, ]); $object->copy($bucket, [ 'name' => $newObjectName, ]); printf( 'Generation %s of object %s in bucket %s was copied to %s', $generationToCopy, $objectToCopy, $bucketName, $newObjectName );}Python
fromgoogle.cloudimportstoragedefcopy_file_archived_generation(bucket_name,blob_name,destination_bucket_name,destination_blob_name,generation):"""Copies a blob from one bucket to another with a new name with the same generation."""# bucket_name = "your-bucket-name"# blob_name = "your-object-name"# destination_bucket_name = "destination-bucket-name"# destination_blob_name = "destination-object-name"# generation = 1579287380533984storage_client=storage.Client()source_bucket=storage_client.bucket(bucket_name)source_blob=source_bucket.blob(blob_name)destination_bucket=storage_client.bucket(destination_bucket_name)# Optional: set a generation-match precondition to avoid potential race conditions# and data corruptions. The request to copy is aborted if the object's# generation number does not match your precondition. For a destination# object that does not yet exist, set the if_generation_match precondition to 0.# If the destination object already exists in your bucket, set instead a# generation-match precondition using its generation number.destination_generation_match_precondition=0# source_generation selects a specific revision of the source object, as opposed to the latest version.blob_copy=source_bucket.copy_blob(source_blob,destination_bucket,destination_blob_name,source_generation=generation,if_generation_match=destination_generation_match_precondition)print("Generation{} of the blob{} in bucket{} copied to blob{} in bucket{}.".format(generation,source_blob.name,source_bucket.name,blob_copy.name,destination_bucket.name,))Ruby
defcopy_file_archived_generationsource_bucket_name:,source_file_name:,generation:,destination_bucket_name:,destination_file_name:# The ID of the bucket the original object is in# source_bucket_name = "source-bucket-name"# The ID of the GCS object to copy# source_file_name = "source-file-name"# The generation of your GCS object to copy# generation = 1579287380533984# The ID of the bucket to copy the object to# destination_bucket_name = "destination-bucket-name"# The ID of the new GCS object# destination_file_name = "destination-file-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newsource_bucket=storage.bucketsource_bucket_name,skip_lookup:truesource_file=source_bucket.filesource_file_namedestination_bucket=storage.bucketdestination_bucket_name,skip_lookup:truedestination_file=source_file.copydestination_bucket,destination_file_name,generation:generationputs"Generation#{generation} of the file#{source_file.name} in bucket#{source_bucket.name} copied to file "\"#{destination_file.name} in bucket#{destination_bucket.name}"end
REST APIs
JSON API
Have gcloud CLIinstalled and initialized, which lets you generate an access token for the
Authorizationheader.Use
cURLto call theJSON API with aPOSTObject request:curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Length: 0" \ "https://storage.googleapis.com/upload/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME/rewriteTo/b/BUCKET_NAME/o/OBJECT_NAME?sourceGeneration=GENERATION_NUMBER"
Where:
BUCKET_NAMEis the name of the bucketcontaining the noncurrent version you want to restore. Forexample,my-bucket.OBJECT_NAMEis the URL-encoded name of thenoncurrent version you want to restore. For example,pets/dog.png, URL-encoded aspets%2Fdog.png.GENERATION_NUMBERis thegeneration number for the noncurrent version you want torestore. For example,1560468815691234.
XML API
Have gcloud CLIinstalled and initialized, which lets you generate an access token for the
Authorizationheader.Use
cURLto call theXML API, with aPUTObject request:curl -X PUT \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "x-goog-copy-source:BUCKET_NAME/OBJECT_NAME" \ -H "x-goog-copy-source-generation:GENERATION_NUMBER" \ "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"
Where:
BUCKET_NAMEis the name of the bucketcontaining the noncurrent version you want to restore. Forexample,my-bucket.OBJECT_NAMEis the URL-encoded name of thenoncurrent version you want to restore. For example,pets/dog.png, URL-encoded aspets%2Fdog.png.GENERATION_NUMBERis thegeneration number for the noncurrent version you want torestore. For example,1560468815691234.
After restoring the object version, the original noncurrent version continues toexist in the bucket. If you no longer need the noncurrent version, you cansubsequently delete it or configureObject Lifecycyle Management to removeit when it meets the conditions you specify.
Delete noncurrent object versions
Console
Note: The Google Cloud console has a limit of 1000 versions of an objectthat it can list.- In the Google Cloud console, go to the Cloud StorageBuckets page.
In the list of buckets, click the name of the bucket that containsthe wanted object.
TheBucket details page opens, with theObjects tab selected.
To view noncurrent objects, click theShow drop-down and selectLive and noncurrent objects.
Navigate to the object, which may be located in a folder.
In the list of objects, click the name of the object whose version youwant to delete.
TheObject details page opens, with theLive Object tabselected.
Click theVersion history tab.
Select the checkbox for the wanted version.
Click theDelete button.
The delete version pane opens.
Confirm you want to delete the object by typing
deleteinto the textfield.ClickDelete.
Command line
Use thegcloud storage rm command:
gcloud storage rm gs://BUCKET_NAME/OBJECT_NAME#GENERATION_NUMBER
Where:
BUCKET_NAMEis the name of the bucketcontaining the noncurrent version you want to delete. For example,my-bucket.OBJECT_NAMEis the name of the noncurrentversion you want to delete. For example,pets/dog.png.GENERATION_NUMBERis thegeneration numberfor the noncurrent version you want to delete. For example,1560468815691234.
If successful, the response looks like the following example:
Operation completed over 1 objects.
--all-versions flag and omitting the#GENERATION_NUMBER. You can removeallversions ofall objects (and potentially the bucket itself) byusing the--recursive flag.Client libraries
For more information, see theCloud StorageC++ API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageC# API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageGo API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageJava API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageNode.js API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StoragePHP API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StoragePython API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. For more information, see theCloud StorageRuby API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.C++
namespacegcs=::google::cloud::storage;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name,std::int64_tobject_generation){google::cloud::Statusstatus=client.DeleteObject(bucket_name,object_name,gcs::Generation{object_generation});if(!status.ok())throwstd::runtime_error(status.message());std::cout <<"Deleted " <<object_name <<" generation " <<object_generation <<" in bucket " <<bucket_name <<"\n";}C#
usingGoogle.Cloud.Storage.V1;usingSystem;publicclassDeleteFileArchivedGenerationSample{publicvoidDeleteFileArchivedGeneration(stringbucketName="your-bucket-name",stringobjectName="your-object-name",long?generation=1579287380533984){varstorage=StorageClient.Create();storage.DeleteObject(bucketName,objectName,newDeleteObjectOptions{Generation=generation});Console.WriteLine($"Generation ${generation} of file {objectName} was deleted from bucket {bucketName}.");}}Go
import("context""fmt""io""time""cloud.google.com/go/storage")// deleteOldVersionOfObject deletes a noncurrent version of an object.funcdeleteOldVersionOfObject(wio.Writer,bucketName,objectNamestring,genint64)error{// bucketName := "bucket-name"// objectName := "object-name"// gen is the generation of objectName to delete.// gen := 1587012235914578ctx:=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()obj:=client.Bucket(bucketName).Object(objectName)iferr:=obj.Generation(gen).Delete(ctx);err!=nil{returnfmt.Errorf("Bucket(%q).Object(%q).Generation(%v).Delete: %w",bucketName,objectName,gen,err)}fmt.Fprintf(w,"Generation %v of object %v was deleted from %v\n",gen,objectName,bucketName)returnnil}Java
importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassDeleteOldVersionOfObject{publicstaticvoiddeleteOldVersionOfObject(StringprojectId,StringbucketName,StringobjectName,longgenerationToDelete){// 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";// The generation of objectName to delete// long generationToDelete = 1579287380533984;Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();storage.delete(BlobId.of(bucketName,objectName,generationToDelete));System.out.println("Generation "+generationToDelete+" of object "+objectName+" was deleted from "+bucketName);}}Node.js
/** * 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';// The generation of fileName to delete// const generation = 1579287380533984;// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiondeleteOldVersionOfFile(){// Deletes the file from the bucket with given versionawaitstorage.bucket(bucketName).file(fileName,{generation,}).delete();console.log(`Generation${generation} of file${fileName} was deleted from${bucketName}`);}deleteOldVersionOfFile().catch(console.error);PHP
use Google\Cloud\Storage\StorageClient;/** * Delete an archived generation of the given 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') * @param string $generationToDelete the generation of the object to delete. * (e.g. 1579287380533984) */function delete_file_archived_generation(string $bucketName, string $objectName, string $generationToDelete): void{ $storage = new StorageClient(); $bucket = $storage->bucket($bucketName); $object = $bucket->object($objectName, [ 'generation' => $generationToDelete, ]); $object->delete(); printf( 'Generation %s of object %s was deleted from %s', $generationToDelete, $objectName, $bucketName );}Python
fromgoogle.cloudimportstoragedefdelete_file_archived_generation(bucket_name,blob_name,generation):"""Delete a blob in the bucket with the given generation."""# bucket_name = "your-bucket-name"# blob_name = "your-object-name"# generation = 1579287380533984storage_client=storage.Client()bucket=storage_client.get_bucket(bucket_name)bucket.delete_blob(blob_name,generation=generation)print(f"Generation{generation} of blob{blob_name} was deleted from{bucket_name}")Ruby
defdelete_file_archived_generationbucket_name:,file_name:,generation:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of your GCS object# file_name = "your-file-name"# The generation of the file to delete# generation = 1579287380533984require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_name,skip_lookup:truefile=bucket.filefile_namefile.deletegeneration:generationputs"Generation#{generation} of file#{file_name} was deleted from#{bucket_name}"end
REST APIs
JSON API
Have gcloud CLIinstalled and initialized, which lets you generate an access token for the
Authorizationheader.Use
cURLto call theJSON API with aDELETEObject request:curl -X DELETE \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?generation=GENERATION_NUMBER"
Where:
BUCKET_NAMEis the name of the bucketcontaining the noncurrent version you want to delete. For example,my-bucket.OBJECT_NAMEis the URL-encoded name of thenoncurrent version you want to delete. For example,pets/dog.png, URL-encoded aspets%2Fdog.png.GENERATION_NUMBERis thegeneration number for the noncurrent version you want todelete. For example,1560468815691234.
XML API
Have gcloud CLIinstalled and initialized, which lets you generate an access token for the
Authorizationheader.Use
cURLto call theXML API, with aDELETEObject request:curl -X DELETE \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME?generation=GENERATION_NUMBER"
Where:
BUCKET_NAMEis the name of the bucketcontaining the noncurrent version you want to delete. For example,my-bucket.OBJECT_NAMEis the URL-encoded name of thenoncurrent version you want to delete. For example,pets/dog.png, URL-encoded aspets%2Fdog.png.GENERATION_NUMBERis thegeneration number for the noncurrent version you want todelete. For example,1560468815691234.
What's next
- Learn more aboutObject Versioning, including anin-depth example.
- Learn how todisable Object Versioning on a bucket.
- Learn how touse Object Lifecycle Management to automatically manageobject versions.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.