This page describes how to use the Object Retention Lock feature, including
enabling it for a bucket and setting retention configurations for objects
within the bucket.
Required roles
To get the permissions that you need to enable the Object Retention Lock feature
for a bucket and set retention configurations on objects, ask your administrator
to grant you the Storage Admin (roles/storage.admin) IAM role
on the bucket or the project that contains the bucket. Thispredefined rolecontains the permissions
required to set and manage retention configurations. To see the exact
permissions that are required, expand theRequired permissionssection:
Required permissions
storage.buckets.create
storage.buckets.enableObjectRetention
storage.buckets.get
storage.buckets.list
This permission is only required if you plan on using the
Google Cloud console to perform the instructions on this page.
storage.objects.get
storage.objects.list
This permission is only required if you plan on using the
Google Cloud console to perform the instructions on this page.
storage.objects.overrideUnlockedRetention
This permission is only required if you plan on locking or shortening
an existing retention configuration.
storage.objects.setRetention
storage.objects.update
You might also be able to get these permissions withcustom roles.
Use the following instructions to allow retention configurations for objects in
a bucket. If you want to enable object retention configurations for an existing
bucket, you must follow the Google Cloud console instructions.
Console
To enable object retention configurations for a new bucket:
Create a bucketas you normally would, and in theChoose how to
protect object datastep, selectRetention (For compliance)followed byEnable object retention.
To enable object retention configurations for an existing bucket:
In the Google Cloud console, go to the Cloud StorageBucketspage.
//! [create-bucket-with-object-retention]namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&project_id){autobucket=client.CreateBucket(bucket_name,gcs::BucketMetadata{},gcs::EnableObjectRetention(true),gcs::OverrideDefaultProject(project_id));if(!bucket)throwstd::move(bucket).status();if(!bucket->has_object_retention()){throwstd::runtime_error("missing object retention in new bucket");}std::cout<<"Successfully created bucket "<<bucket_name<<" with object retention: "<<bucket->object_retention()<<"\n";}//! [create-bucket-with-object-retention]
importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.BucketInfo;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassCreateBucketWithObjectRetention{publicstaticvoidcreateBucketWithObjectRetention(StringprojectId,StringbucketName){// The ID of your GCP project// String projectId = "your-project-id";// The ID to give your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Bucketbucket=storage.create(BucketInfo.of(bucketName),Storage.BucketTargetOption.enableObjectRetention(true));System.out.println("Created bucket "+bucket.getName()+" with object retention enabled setting: "+bucket.getObjectRetention().getMode().toString());}}
/*** 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 client// The bucket in the sample below will be created in the project associated with this client.// For more information, please see https://cloud.google.com/docs/authentication/production or https://googleapis.dev/nodejs/storage/latest/Storage.htmlconststorage=newStorage();asyncfunctioncreateBucketWithObjectRetention(){const[bucket]=awaitstorage.createBucket(bucketName,{enableObjectRetention:true,});console.log(`Created '${bucket.name}' with object retention enabled setting:${bucket.metadata.objectRetention.mode}`);}createBucketWithObjectRetention().catch(console.error);
use Google\Cloud\Storage\StorageClient;/*** Create a Cloud Storage bucket with the object retention enabled.** @param string $bucketName The name of your Cloud Storage bucket.* (e.g. 'my-bucket')*/function create_bucket_with_object_retention(string $bucketName): void{$storage = new StorageClient();$bucket = $storage->createBucket($bucketName, ['enableObjectRetention' => true]);printf('Created bucket %s with object retention enabled setting: %s' . PHP_EOL,$bucketName,$bucket->info()['objectRetention']['mode']);}
fromgoogle.cloudimportstoragedefcreate_bucket_object_retention(bucket_name):"""Creates a bucket with object retention enabled."""# The ID of your GCS bucket# bucket_name = "your-bucket-name"storage_client=storage.Client()bucket=storage_client.create_bucket(bucket_name,enable_object_retention=True)print(f"Created bucket{bucket_name}with object retention enabled setting:{bucket.object_retention_mode}")
REST APIs
JSON API
Create a bucketas you normally would, and include the query
parameterenableObjectRetention=trueas part of the request.
XML API
Create a bucketas you normally would, and include the headerx-goog-bucket-object-lock-enabled: Trueas part of the request.
View a bucket's object retention status
To see if retention configurations can be set for objects in a bucket:
Console
In the Google Cloud console, go to the Cloud StorageBucketspage.
To view a bucket's object retention configuration, follow the instructions for displaying a bucket's metadata and look for
the object retention field in the response.
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name){StatusOr<gcs::BucketMetadata>bucket_metadata=client.GetBucketMetadata(bucket_name);if(!bucket_metadata)throwstd::move(bucket_metadata).status();std::cout<<"The metadata for bucket "<<bucket_metadata->name()<<" is "<<*bucket_metadata<<"\n";}
To view a bucket's object retention configuration, follow the instructions for displaying a bucket's metadata and look for
the object retention field in the response.
To view a bucket's object retention configuration, follow the instructions for displaying a bucket's metadata and look for
the object retention field in the response.
importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.BucketInfo;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.util.Map;publicclassGetBucketMetadata{publicstaticvoidgetBucketMetadata(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();// Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAMEBucketbucket=storage.get(bucketName,Storage.BucketGetOption.fields(Storage.BucketField.values()));// Print bucket metadataSystem.out.println("BucketName: "+bucket.getName());System.out.println("DefaultEventBasedHold: "+bucket.getDefaultEventBasedHold());System.out.println("DefaultKmsKeyName: "+bucket.getDefaultKmsKeyName());System.out.println("Id: "+bucket.getGeneratedId());System.out.println("IndexPage: "+bucket.getIndexPage());System.out.println("Location: "+bucket.getLocation());System.out.println("LocationType: "+bucket.getLocationType());System.out.println("Metageneration: "+bucket.getMetageneration());System.out.println("NotFoundPage: "+bucket.getNotFoundPage());System.out.println("RetentionEffectiveTime: "+bucket.getRetentionEffectiveTime());System.out.println("RetentionPeriod: "+bucket.getRetentionPeriod());System.out.println("RetentionPolicyIsLocked: "+bucket.retentionPolicyIsLocked());System.out.println("RequesterPays: "+bucket.requesterPays());System.out.println("SelfLink: "+bucket.getSelfLink());System.out.println("StorageClass: "+bucket.getStorageClass().name());System.out.println("TimeCreated: "+bucket.getCreateTime());System.out.println("VersioningEnabled: "+bucket.versioningEnabled());System.out.println("ObjectRetention: "+bucket.getObjectRetention());if(bucket.getLabels()!=null){System.out.println("\n\n\nLabels:");for(Map.Entry<String,String>label:bucket.getLabels().entrySet()){System.out.println(label.getKey()+"="+label.getValue());}}if(bucket.getLifecycleRules()!=null){System.out.println("\n\n\nLifecycle Rules:");for(BucketInfo.LifecycleRulerule:bucket.getLifecycleRules()){System.out.println(rule);}}}}
To view a bucket's object retention configuration, follow the instructions for displaying a bucket's metadata and look for
the object retention field in the response.
// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiongetBucketMetadata(){/*** TODO(developer): Uncomment the following lines before running the sample.*/// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// Get Bucket Metadataconst[metadata]=awaitstorage.bucket(bucketName).getMetadata();console.log(JSON.stringify(metadata,null,2));}
To view a bucket's object retention configuration, follow the instructions for displaying a bucket's metadata and look for
the object retention field in the response.
use Google\Cloud\Storage\StorageClient;/*** Get bucket metadata.** @param string $bucketName The name of your Cloud Storage bucket.* (e.g. 'my-bucket')*/function get_bucket_metadata(string $bucketName): void{$storage = new StorageClient();$bucket = $storage->bucket($bucketName);$info = $bucket->info();printf('Bucket Metadata: %s' . PHP_EOL, print_r($info, true));}
To view a bucket's object retention configuration, follow the instructions for displaying a bucket's metadata and look for
the object retention field in the response.
fromgoogle.cloudimportstoragedefbucket_metadata(bucket_name):"""Prints out a bucket's metadata."""# bucket_name = 'your-bucket-name'storage_client=storage.Client()bucket=storage_client.get_bucket(bucket_name)print(f"ID:{bucket.id}")print(f"Name:{bucket.name}")print(f"Storage Class:{bucket.storage_class}")print(f"Location:{bucket.location}")print(f"Location Type:{bucket.location_type}")print(f"Cors:{bucket.cors}")print(f"Default Event Based Hold:{bucket.default_event_based_hold}")print(f"Default KMS Key Name:{bucket.default_kms_key_name}")print(f"Metageneration:{bucket.metageneration}")print(f"Public Access Prevention:{bucket.iam_configuration.public_access_prevention}")print(f"Retention Effective Time:{bucket.retention_policy_effective_time}")print(f"Retention Period:{bucket.retention_period}")print(f"Retention Policy Locked:{bucket.retention_policy_locked}")print(f"Object Retention Mode:{bucket.object_retention_mode}")print(f"Requester Pays:{bucket.requester_pays}")print(f"Self Link:{bucket.self_link}")print(f"Time Created:{bucket.time_created}")print(f"Versioning Enabled:{bucket.versioning_enabled}")print(f"Labels:{bucket.labels}")
WhereBUCKET_NAMEis the name of the
relevant bucket. For example,my-bucket.
Set an object's retention configuration
In order to set a retention configuration for an object, the object must be
stored in a bucket for whichobject retentions are enabled. To set a
retention configuration for an object:
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 object whose retention configuration you want to set or modify.
TheBucket detailspage opens, with theObjectstab selected.
Navigate to the object, which might be located in a folder.
Click the name of the object.
TheObject detailspage opens, which displays object metadata.
In theProtectionsection, click theEditicon
(edit)
associated withFrom object retention configuration.
TheEdit retentionpane opens.
In theObject retention configurationsection, clickEnabledorDisabled.
If the retention configuration is enabled, select a date and time
for the configuration in theRetain until timesection, and
clickUnlockedorLockedin theRetention modesection.
ClickConfirm.
Command line
Use thegcloud storage objects updatecommand with the
appropriate flags. To add or modify a retention configuration, use the
following command. Note that you must additionally include the--override-unlocked-retentionflag if you are modifying an existing
configuration in a way that locks it or shortens its retain-until time:
usingGoogle.Cloud.Storage.V1;usingSystem;usingObject=Google.Apis.Storage.v1.Data.Object;publicclassSetObjectRetentionPolicySample{publicGoogle.Apis.Storage.v1.Data.ObjectSetObjectRetentionPolicy(stringbucketName="your-unique-bucket-name",// A bucket that has object retention enabledstringobjectName="your-object-name")// An object that does not have a retention policy set{varstorage=StorageClient.Create();varfile=storage.GetObject(bucketName,objectName);file.Retention=newObject.RetentionData{Mode="Unlocked",RetainUntilTimeDateTimeOffset=DateTimeOffset.UtcNow.AddDays(10)};file=storage.UpdateObject(file);Console.WriteLine($"The retention policy for object {objectName} was set to:");Console.WriteLine("Mode: "+file.Retention.Mode);Console.WriteLine("RetainUntilTime: "+file.Retention.RetainUntilTimeDateTimeOffset.ToString());// To modify an existing policy on an Unlocked object, pass in the override parameterfile.Retention=newObject.RetentionData{Mode="Unlocked",RetainUntilTimeDateTimeOffset=DateTimeOffset.UtcNow.AddDays(9)};file=storage.UpdateObject(file,newUpdateObjectOptions{OverrideUnlockedRetention=true});Console.WriteLine($"The retention policy for object {objectName} was updated to:");Console.WriteLine("Mode: "+file.Retention.Mode);Console.WriteLine("RetainUntilTime: "+file.Retention.RetainUntilTimeDateTimeOffset.ToString());returnfile;}}
import staticjava.time.OffsetDateTime.now;importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.BlobInfo.Retention;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;publicclassSetObjectRetentionPolicy{publicstaticvoidsetObjectRetentionPolicy(StringprojectId,StringbucketName,StringobjectName)throwsStorageException{// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket that has object retention enabled// String bucketName = "your-unique-bucket-name";// The ID of your GCS object// String objectName = "your-object-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();BlobIdblobId=BlobId.of(bucketName,objectName);Blobblob=storage.get(blobId);if(blob==null){System.out.println("The object "+objectName+" was not found in "+bucketName);return;}Blobupdated=blob.toBuilder().setRetention(Retention.newBuilder().setMode(Retention.Mode.UNLOCKED).setRetainUntilTime(now().plusDays(10)).build()).build().update();System.out.println("Retention policy for object "+objectName+" was set to:");System.out.println(updated.getRetention().toString());// To modify an existing policy on an Unlocked object, pass in the override parameterblob.toBuilder().setRetention(updated.getRetention().toBuilder().setRetainUntilTime(now().plusDays(9)).build()).build().update(Storage.BlobTargetOption.overrideUnlockedRetention(true));System.out.println("Retention policy for object "+objectName+" was updated to:");System.out.println(storage.get(blobId).getRetention().toString());}}
/*** TODO(developer): Uncomment the following lines before running the sample.*/// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The new ID for your GCS file// const destFileName = 'your-new-file-name';// The content to be uploaded in the GCS file// const contents = 'your file content';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a client// The bucket in the sample below will be created in the project associated with this client.// For more information, please see https://cloud.google.com/docs/authentication/production or https://googleapis.dev/nodejs/storage/latest/Storage.htmlconststorage=newStorage();asyncfunctionsetObjectRetentionPolicy(){// Get a reference to the bucketconstmyBucket=storage.bucket(bucketName);// Create a reference to a file objectconstfile=myBucket.file(destFileName);// Save the file dataawaitfile.save(contents);// Set the retention policy for the fileconstretentionDate=newDate();retentionDate.setDate(retentionDate.getDate()+10);const[metadata]=awaitfile.setMetadata({retention:{mode:'Unlocked',retainUntilTime:retentionDate.toISOString(),},});console.log(`Retention policy for file${file.name}was set to:${metadata.retention.mode}`);// To modify an existing policy on an unlocked file object, pass in the override parameterconstnewRetentionDate=newDate(retentionDate.getDate());newRetentionDate.setDate(newRetentionDate.getDate()+9);const[newMetadata]=awaitfile.setMetadata({retention:{mode:'Unlocked',retainUntilTime:newRetentionDate,},overrideUnlockedRetention:true,});console.log(`Retention policy for file${file.name}was updated to:${newMetadata.retention.retainUntilTime}`);}setObjectRetentionPolicy().catch(console.error);
use Google\Cloud\Storage\StorageClient;/*** Sets a bucket's retention policy.** @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 set_object_retention_policy(string $bucketName, string $objectName): void{$storage = new StorageClient();$bucket = $storage->bucket($bucketName);$object = $bucket->object($objectName);$expires = (new \DateTime)->add(\DateInterval::createFromDateString('+10 days'));// To modify an existing policy on an Unlocked object, pass the override parameter$object->update(['retention' => ['mode' => 'Unlocked','retainUntilTime' => $expires->format(\DateTime::RFC3339)],'overrideUnlockedRetention' => true]);printf('Retention policy for object %s was updated to: %s' . PHP_EOL,$objectName,$object->info()['retention']['retainUntilTime']);}
fromgoogle.cloudimportstoragedefset_object_retention_policy(bucket_name,contents,destination_blob_name):"""Set the object retention policy of a file."""# The ID of your GCS bucket# bucket_name = "your-bucket-name"# The contents to upload to the file# contents = "these are my contents"# The ID of your GCS object# destination_blob_name = "storage-object-name"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)blob=bucket.blob(destination_blob_name)blob.upload_from_string(contents)# Set the retention policy for the file.blob.retention.mode="Unlocked"retention_date=datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(days=10)blob.retention.retain_until_time=retention_dateblob.patch()print(f"Retention policy for file{destination_blob_name}was set to:{blob.retention.mode}.")# To modify an existing policy on an unlocked file object, pass in the override parameter.new_retention_date=datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(days=9)blob.retention.retain_until_time=new_retention_dateblob.patch(override_unlocked_retention=True)print(f"Retention policy for file{destination_blob_name}was updated to:{blob.retention.retain_until_time}.")
JSON_FILE_NAMEis the path for the file
that you created in Step 2.
BUCKET_NAMEis the name of the relevant
bucket. For example,my-bucket.
OBJECT_NAMEis the URL-encoded name of the
relevant object. For example,pets/kitten.png, URL-encoded aspets%2Fkitten.png.
BOOLEANmust betrueif the request
shortens, removes, or locks an existing retention configuration.
Otherwise, theoverrideUnlockedRetentionparameter can be
excluded from the request entirely.
XML_FILE_NAMEis the path for the XML
file that you created in Step 2.
BOOLEANmust betrueif the request
shortens, removes, or locks an existing retention configuration.
Otherwise, thex-goog-bypass-governance-retentionheader can be
excluded from the request entirely.
BUCKET_NAMEis the name of the relevant
bucket. For example,my-bucket.
OBJECT_NAMEis the URL-encoded name of the
relevant object. For example,pets/kitten.png, URL-encoded aspets%2Fkitten.png.
View an object's retention configuration
To view what, if any, retention configuration is set on an object:
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 object whose retention configuration you want to view.
TheBucket detailspage opens, with theObjectstab selected.
Navigate to the object, which might be located in a folder.
Click the name of the object.
TheObject detailspage opens, which displays object metadata.
Information about any retention configuration the object has is shown
in theProtectionsection.
To view an object's retention configuration, follow the instructions for displaying a object's metadata and look for
the retention field in the response.
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name){StatusOr<gcs::ObjectMetadata>object_metadata=client.GetObjectMetadata(bucket_name,object_name);if(!object_metadata)throwstd::move(object_metadata).status();std::cout<<"The metadata for object "<<object_metadata->name()<<" in bucket "<<object_metadata->bucket()<<" is "<<*object_metadata<<"\n";}
To view an object's retention configuration, follow the instructions for displaying a object's metadata and look for
the retention field in the response.
usingGoogle.Cloud.Storage.V1;usingSystem;publicclassGetMetadataSample{publicGoogle.Apis.Storage.v1.Data.ObjectGetMetadata(stringbucketName="your-unique-bucket-name",stringobjectName="your-object-name"){varstorage=StorageClient.Create();varstorageObject=storage.GetObject(bucketName,objectName,newGetObjectOptions{Projection=Projection.Full});Console.WriteLine($"Bucket:\t{storageObject.Bucket}");Console.WriteLine($"CacheControl:\t{storageObject.CacheControl}");Console.WriteLine($"ComponentCount:\t{storageObject.ComponentCount}");Console.WriteLine($"ContentDisposition:\t{storageObject.ContentDisposition}");Console.WriteLine($"ContentEncoding:\t{storageObject.ContentEncoding}");Console.WriteLine($"ContentLanguage:\t{storageObject.ContentLanguage}");Console.WriteLine($"ContentType:\t{storageObject.ContentType}");Console.WriteLine($"Crc32c:\t{storageObject.Crc32c}");Console.WriteLine($"ETag:\t{storageObject.ETag}");Console.WriteLine($"Generation:\t{storageObject.Generation}");Console.WriteLine($"Id:\t{storageObject.Id}");Console.WriteLine($"Kind:\t{storageObject.Kind}");Console.WriteLine($"KmsKeyName:\t{storageObject.KmsKeyName}");Console.WriteLine($"Md5Hash:\t{storageObject.Md5Hash}");Console.WriteLine($"MediaLink:\t{storageObject.MediaLink}");Console.WriteLine($"Metageneration:\t{storageObject.Metageneration}");Console.WriteLine($"Name:\t{storageObject.Name}");Console.WriteLine($"Retention:\t{storageObject.Retention}");Console.WriteLine($"Size:\t{storageObject.Size}");Console.WriteLine($"StorageClass:\t{storageObject.StorageClass}");Console.WriteLine($"TimeCreated:\t{storageObject.TimeCreated}");Console.WriteLine($"Updated:\t{storageObject.Updated}");booleventBasedHold=storageObject.EventBasedHold??false;Console.WriteLine("Event-based hold enabled? {0}",eventBasedHold);booltemporaryHold=storageObject.TemporaryHold??false;Console.WriteLine("Temporary hold enabled? {0}",temporaryHold);Console.WriteLine($"RetentionExpirationTime\t{storageObject.RetentionExpirationTime}");if(storageObject.Metadata!=null){Console.WriteLine("Metadata: ");foreach(varmetadatainstorageObject.Metadata){Console.WriteLine($"{metadata.Key}:\t{metadata.Value}");}}Console.WriteLine($"CustomTime:\t{storageObject.CustomTime}");returnstorageObject;}}
To view an object's retention configuration, follow the instructions for displaying a object's metadata and look for
the retention field in the response.
importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;importjava.util.Date;importjava.util.Map;publicclassGetObjectMetadata{publicstaticvoidgetObjectMetadata(StringprojectId,StringbucketName,StringblobName)throwsStorageException{// 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();// Select all fields// Fields can be selected individually e.g. Storage.BlobField.CACHE_CONTROLBlobblob=storage.get(bucketName,blobName,Storage.BlobGetOption.fields(Storage.BlobField.values()));// Print blob metadataSystem.out.println("Bucket: "+blob.getBucket());System.out.println("CacheControl: "+blob.getCacheControl());System.out.println("ComponentCount: "+blob.getComponentCount());System.out.println("ContentDisposition: "+blob.getContentDisposition());System.out.println("ContentEncoding: "+blob.getContentEncoding());System.out.println("ContentLanguage: "+blob.getContentLanguage());System.out.println("ContentType: "+blob.getContentType());System.out.println("CustomTime: "+blob.getCustomTime());System.out.println("Crc32c: "+blob.getCrc32c());System.out.println("Crc32cHexString: "+blob.getCrc32cToHexString());System.out.println("ETag: "+blob.getEtag());System.out.println("Generation: "+blob.getGeneration());System.out.println("Id: "+blob.getBlobId());System.out.println("KmsKeyName: "+blob.getKmsKeyName());System.out.println("Md5Hash: "+blob.getMd5());System.out.println("Md5HexString: "+blob.getMd5ToHexString());System.out.println("MediaLink: "+blob.getMediaLink());System.out.println("Metageneration: "+blob.getMetageneration());System.out.println("Name: "+blob.getName());System.out.println("Size: "+blob.getSize());System.out.println("StorageClass: "+blob.getStorageClass());System.out.println("TimeCreated: "+newDate(blob.getCreateTime()));System.out.println("Last Metadata Update: "+newDate(blob.getUpdateTime()));System.out.println("Object Retention Policy: "+blob.getRetention());BooleantemporaryHoldIsEnabled=(blob.getTemporaryHold()!=null&&blob.getTemporaryHold());System.out.println("temporaryHold: "+(temporaryHoldIsEnabled?"enabled":"disabled"));BooleaneventBasedHoldIsEnabled=(blob.getEventBasedHold()!=null&&blob.getEventBasedHold());System.out.println("eventBasedHold: "+(eventBasedHoldIsEnabled?"enabled":"disabled"));if(blob.getRetentionExpirationTime()!=null){System.out.println("retentionExpirationTime: "+newDate(blob.getRetentionExpirationTime()));}if(blob.getMetadata()!=null){System.out.println("\n\n\nUser metadata:");for(Map.Entry<String,String>userMetadata:blob.getMetadata().entrySet()){System.out.println(userMetadata.getKey()+"="+userMetadata.getValue());}}}}
To view an object's retention configuration, follow the instructions for displaying a object's metadata and look for
the retention field in the response.
/*** 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();asyncfunctiongetMetadata(){// Gets the metadata for the fileconst[metadata]=awaitstorage.bucket(bucketName).file(fileName).getMetadata();console.log(`Bucket:${metadata.bucket}`);console.log(`CacheControl:${metadata.cacheControl}`);console.log(`ComponentCount:${metadata.componentCount}`);console.log(`ContentDisposition:${metadata.contentDisposition}`);console.log(`ContentEncoding:${metadata.contentEncoding}`);console.log(`ContentLanguage:${metadata.contentLanguage}`);console.log(`ContentType:${metadata.contentType}`);console.log(`CustomTime:${metadata.customTime}`);console.log(`Crc32c:${metadata.crc32c}`);console.log(`ETag:${metadata.etag}`);console.log(`Generation:${metadata.generation}`);console.log(`Id:${metadata.id}`);console.log(`KmsKeyName:${metadata.kmsKeyName}`);console.log(`Md5Hash:${metadata.md5Hash}`);console.log(`MediaLink:${metadata.mediaLink}`);console.log(`Metageneration:${metadata.metageneration}`);console.log(`Name:${metadata.name}`);console.log(`Size:${metadata.size}`);console.log(`StorageClass:${metadata.storageClass}`);console.log(`TimeCreated:${newDate(metadata.timeCreated)}`);console.log(`Last Metadata Update:${newDate(metadata.updated)}`);console.log(`TurboReplication:${metadata.rpo}`);console.log(`temporaryHold:${metadata.temporaryHold?'enabled':'disabled'}`);console.log(`eventBasedHold:${metadata.eventBasedHold?'enabled':'disabled'}`);if(metadata.retentionExpirationTime){console.log(`retentionExpirationTime:${newDate(metadata.retentionExpirationTime)}`);}if(metadata.metadata){console.log('\n\n\nUser metadata:');for(constkeyinmetadata.metadata){console.log(`${key}=${metadata.metadata[key]}`);}}}getMetadata().catch(console.error);
To view an object's retention configuration, follow the instructions for displaying a object's metadata and look for
the retention field in the response.
To view an object's retention configuration, follow the instructions for displaying a object's metadata and look for
the retention field in the response.
fromgoogle.cloudimportstoragedefblob_metadata(bucket_name,blob_name):"""Prints out a blob's metadata."""# bucket_name = 'your-bucket-name'# blob_name = 'your-object-name'storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)# Retrieve a blob, and its metadata, from Google Cloud Storage.# Note that `get_blob` differs from `Bucket.blob`, which does not# make an HTTP request.blob=bucket.get_blob(blob_name)print(f"Blob:{blob.name}")print(f"Bucket:{blob.bucket.name}")print(f"Storage class:{blob.storage_class}")print(f"ID:{blob.id}")print(f"Size:{blob.size}bytes")print(f"Updated:{blob.updated}")print(f"Generation:{blob.generation}")print(f"Metageneration:{blob.metageneration}")print(f"Etag:{blob.etag}")print(f"Owner:{blob.owner}")print(f"Component count:{blob.component_count}")print(f"Crc32c:{blob.crc32c}")print(f"md5_hash:{blob.md5_hash}")print(f"Cache-control:{blob.cache_control}")print(f"Content-type:{blob.content_type}")print(f"Content-disposition:{blob.content_disposition}")print(f"Content-encoding:{blob.content_encoding}")print(f"Content-language:{blob.content_language}")print(f"Metadata:{blob.metadata}")print(f"Medialink:{blob.media_link}")print(f"Custom Time:{blob.custom_time}")print("Temporary hold: ","enabled"ifblob.temporary_holdelse"disabled")print("Event based hold: ","enabled"ifblob.event_based_holdelse"disabled",)print(f"Retention mode:{blob.retention.mode}")print(f"Retention retain until time:{blob.retention.retain_until_time}")ifblob.retention_expiration_time:print(f"retentionExpirationTime:{blob.retention_expiration_time}")
[[["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 2025-09-04 UTC."],[],[],null,[]]