Use and lock retention policies
Stay organized with collections
Save and categorize content based on your preferences.
This page describes how to use the Bucket Lock feature, including working with retention policies and permanently locking them on buckets.
Before you begin
Before you can use the Bucket Lock feature, make sure the steps in the following sections have been completed.
Get required roles
To get the permissions that you need to use Bucket Lock, ask your
administrator to grant you the Storage Admin (roles/storage.admin) role on the
bucket. This predefined role contains the permissions required to use
Bucket Lock. To see the exact permissions required, expand the
Required permissions section:
Required permissions
storage.buckets.getstorage.buckets.list- This permission is only required if you plan on using the Google Cloud console to perform the instructions on this page.
storage.buckets.update
You might also be able to get these permissions with custom roles.
For information about granting roles on buckets, see Set and manage IAM policies on buckets.
Set a retention policy on a bucket
To add, modify, or remove a retention policy on a bucket:
Console
- In the Google Cloud console, go to the Cloud Storage Buckets page.
In the list of buckets, click the name of the bucket whose retention policy you want to change.
Select the Protection tab near the top of the page.
In the Retention policy section, set your retention policy:
If no retention policy currently applies to the bucket, click the add_box Set Retention Policy link. Choose a unit of time and a length of time for your retention period.
If a retention policy currently applies to a bucket, it appears in the section. Click Edit to modify the retention time or Delete to remove the retention policy entirely.
See Retention periods for information about how the Google Cloud console converts between different units of time.
To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, see Troubleshooting.
Command line
Use the gcloud storage buckets update command with the
appropriate flag:
gcloud storage buckets update gs://BUCKET_NAME FLAG
Where:
BUCKET_NAMEis the name of the relevant bucket. For example,my-bucket.FLAGis the desired setting for the bucket's retention period. Use one of the following formats:--retention-periodand a retention period, if you want to add or change a retention policy. For example,--retention-period=1d43200s.--clear-retention-period, if you want to remove the retention policy on the bucket.
If successful, the response looks like:
Updating gs://my-bucket/... Completed 1
Client libraries
For more information, see the
Cloud Storage C++ API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
The following sample sets a retention policy on a bucket: The following sample removes the retention policy from a bucket:
For more information, see the
Cloud Storage C# API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
The following sample sets a retention policy on a bucket: The following sample removes the retention policy from a bucket:
For more information, see the
Cloud Storage Go API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
The following sample sets a retention policy on a bucket: The following sample removes the retention policy from a bucket:
For more information, see the
Cloud Storage Java API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
The following sample sets a retention policy on a bucket: The following sample removes the retention policy from a bucket:
For more information, see the
Cloud Storage Node.js API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
The following sample sets a retention policy on a bucket: The following sample removes the retention policy from a bucket:
For more information, see the
Cloud Storage PHP API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
The following sample sets a retention policy on a bucket: The following sample removes the retention policy from a bucket:
For more information, see the
Cloud Storage Python API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
The following sample sets a retention policy on a bucket: The following sample removes the retention policy from a bucket:
For more information, see the
Cloud Storage Ruby API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
The following sample sets a retention policy on a bucket: The following sample removes the retention policy from a bucket:C++
namespacegcs=::google::cloud::storage;
using::google::cloud::StatusOr;
[](gcs::Clientclient,std::stringconst&bucket_name,
std::chrono::secondsperiod){
StatusOr<gcs::BucketMetadata>original=
client.GetBucketMetadata(bucket_name);
if(!original)throwstd::move(original).status();
StatusOr<gcs::BucketMetadata>patched=client.PatchBucket(
bucket_name,
gcs::BucketMetadataPatchBuilder().SetRetentionPolicy(period),
gcs::IfMetagenerationMatch(original->metageneration()));
if(!patched)throwstd::move(patched).status();
if(!patched->has_retention_policy()){
std::cout << "The bucket " << patched->name()
<< " does not have a retention policy set.\n";
return;
}
std::cout << "The bucket " << patched->name()
<< " retention policy is set to " << patched->retention_policy()
<< "\n";
}namespacegcs=::google::cloud::storage;
using::google::cloud::StatusOr;
[](gcs::Clientclient,std::stringconst&bucket_name){
StatusOr<gcs::BucketMetadata>original=
client.GetBucketMetadata(bucket_name);
if(!original)throwstd::move(original).status();
StatusOr<gcs::BucketMetadata>patched=client.PatchBucket(
bucket_name,gcs::BucketMetadataPatchBuilder().ResetRetentionPolicy(),
gcs::IfMetagenerationMatch(original->metageneration()));
if(!patched)throwstd::move(patched).status();
if(!patched->has_retention_policy()){
std::cout << "The bucket " << patched->name()
<< " does not have a retention policy set.\n";
return;
}
std::cout << "The bucket " << patched->name()
<< " retention policy is set to " << patched->retention_policy()
<< ". This is unexpected, maybe a concurrent change by another"
<< " application?\n";
}C#
usingGoogle.Cloud.Storage.V1 ;
usingSystem;
usingstaticGoogle.Apis.Storage.v1.Data.Bucket;
publicclassSetRetentionPolicySample
{
/// <summary>
/// Sets the bucket's retention policy.
/// </summary>
/// <param name="bucketName">The name of the bucket.</param>
/// <param name="retentionPeriod">The duration in seconds that objects need to be retained. The retention policy enforces a minimum retention
/// time for all objects contained in the bucket, based on their creation time. Any
/// attempt to overwrite or delete objects younger than the retention period will
/// result in a PERMISSION_DENIED error. An unlocked retention policy can be modified
/// or removed from the bucket via a storage.buckets.update operation. A locked retention
/// policy cannot be removed or shortened in duration for the lifetime of the bucket.
/// Attempting to remove or decrease the period of a locked retention policy will result
/// in a PERMISSION_DENIED error.</param>
publicRetentionPolicyDataSetRetentionPolicy(
stringbucketName="your-unique-bucket-name",
longretentionPeriod=10)
{
varstorage=StorageClient .Create ();
varbucket=storage.GetBucket(bucketName);
bucket.RetentionPolicy=newRetentionPolicyData{RetentionPeriod=retentionPeriod};
bucket=storage.UpdateBucket(bucket);
Console.WriteLine($"Retention policy for {bucketName} was set to {retentionPeriod}");
returnbucket.RetentionPolicy;
}
}
usingGoogle.Cloud.Storage.V1 ;
usingSystem;
publicclassRemoveRetentionPolicySample
{
publicvoidRemoveRetentionPolicy(stringbucketName="your-unique-bucket-name")
{
varstorage=StorageClient .Create ();
varbucket=storage.GetBucket(bucketName);
if(bucket.RetentionPolicy!=null)
{
boolisLocked=bucket.RetentionPolicy.IsLocked??false;
if(isLocked)
{
thrownewException("Retention Policy is locked.");
}
bucket.RetentionPolicy.RetentionPeriod=null;
storage.UpdateBucket(bucket);
Console.WriteLine($"Retention period for {bucketName} has been removed.");
}
}
}Go
import(
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/storage"
)
// setRetentionPolicy sets the bucket retention period.
funcsetRetentionPolicy(wio.Writer ,bucketNamestring,retentionPeriodtime.Duration)error{
// bucketName := "bucket-name"
// retentionPeriod := time.Second
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()
bucket:=client.Bucket (bucketName)
bucketAttrsToUpdate:=storage.BucketAttrsToUpdate {
RetentionPolicy:&storage.RetentionPolicy {
RetentionPeriod:retentionPeriod,
},
}
if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{
returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)
}
fmt.Fprintf(w,"Retention policy for %v was set to %v\n",bucketName,bucketAttrsToUpdate.RetentionPolicy .RetentionPeriod)
returnnil
}
import(
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/storage"
)
// removeRetentionPolicy removes bucket retention policy.
funcremoveRetentionPolicy(wio.Writer ,bucketNamestring)error{
// bucketName := "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*50)
defercancel()
bucket:=client.Bucket (bucketName)
attrs,err:=bucket.Attrs(ctx)
iferr!=nil{
returnfmt.Errorf("Bucket(%q).Attrs: %w",bucketName,err)
}
ifattrs.RetentionPolicy .IsLocked{
returnfmt.Errorf("retention policy is locked")
}
bucketAttrsToUpdate:=storage.BucketAttrsToUpdate {
RetentionPolicy:&storage.RetentionPolicy {},
}
if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{
returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)
}
fmt.Fprintf(w,"Retention period for %v has been removed\n",bucketName)
returnnil
}
Java
importcom.google.cloud.storage.Bucket ;
importcom.google.cloud.storage.Storage ;
importcom.google.cloud.storage.Storage.BucketTargetOption ;
importcom.google.cloud.storage.StorageException ;
importcom.google.cloud.storage.StorageOptions ;
importjava.time.Duration;
publicclass SetRetentionPolicy{
publicstaticvoidsetRetentionPolicy(
StringprojectId,StringbucketName,LongretentionPeriodSeconds)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 retention period for objects in bucket
// Long retentionPeriodSeconds = 3600L; // 1 hour in seconds
Storage storage=StorageOptions .newBuilder().setProjectId(projectId).build().getService ();
// first look up the bucket so we will have its metageneration
Bucket bucket=storage.get (bucketName);
Bucket bucketWithRetentionPolicy=
storage.update (
bucket.toBuilder()
.setRetentionPeriodDuration(Duration.ofSeconds(retentionPeriodSeconds))
.build(),
BucketTargetOption.metagenerationMatch());
System.out.println(
"Retention period for "
+bucketName
+" is now "
+bucketWithRetentionPolicy.getRetentionPeriodDuration ());
}
}
importcom.google.cloud.storage.Bucket ;
importcom.google.cloud.storage.Storage ;
importcom.google.cloud.storage.StorageException ;
importcom.google.cloud.storage.StorageOptions ;
publicclass RemoveRetentionPolicy{
publicstaticvoidremoveRetentionPolicy(StringprojectId,StringbucketName)
throwsStorageException ,IllegalArgumentException{
// The ID of your GCP project
// String projectId = "your-project-id";
// The ID of your GCS bucket
// String bucketName = "your-unique-bucket-name";
Storage storage=StorageOptions .newBuilder().setProjectId(projectId).build().getService ();
Bucket bucket=
storage.get (
bucketName,Storage.BucketGetOption.fields(Storage.BucketField.RETENTION_POLICY));
if(bucket.retentionPolicyIsLocked ()!=null && bucket.retentionPolicyIsLocked ()){
thrownewIllegalArgumentException(
"Unable to remove retention policy as retention policy is locked.");
}
bucket.toBuilder ().setRetentionPeriod(null).build().update();
System.out.println("Retention policy for "+bucketName+" has been removed");
}
}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 retention period for objects in bucket
// const retentionPeriod = 3600; // 1 hour in seconds
// Imports the Google Cloud client library
const{Storage}=require('@google-cloud/storage');
// Creates a client
conststorage=newStorage();
asyncfunctionsetRetentionPolicy(){
const[metadata]=awaitstorage
.bucket(bucketName)
.setRetentionPeriod (retentionPeriod);
console.log(
`Bucket ${bucketName} retention period set for ${metadata.retentionPolicy .retentionPeriod} seconds.`
);
}
setRetentionPolicy().catch(console.error);/**
* 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 library
const{Storage}=require('@google-cloud/storage');
// Creates a client
conststorage=newStorage();
asyncfunctionremoveRetentionPolicy(){
const[metadata]=awaitstorage.bucket(bucketName).getMetadata();
if(metadata.retentionPolicy && metadata.retentionPolicy .isLocked){
console.log(
'Unable to remove retention period as retention policy is locked.'
);
returnnull;
}else{
constresults=awaitstorage.bucket(bucketName).removeRetentionPeriod ();
console.log(`Removed bucket ${bucketName} retention policy.`);
returnresults;
}
}
removeRetentionPolicy().catch(console.error);PHP
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 int $retentionPeriod The retention period for objects in bucket, in seconds.
* (e.g. 3600)
*/
function set_retention_policy(string $bucketName, int $retentionPeriod): void
{
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$bucket->update([
'retentionPolicy' => [
'retentionPeriod' => $retentionPeriod
]]);
printf('Bucket %s retention period set to %s seconds' . PHP_EOL, $bucketName,
$retentionPeriod);
}use Google\Cloud\Storage\StorageClient;
/**
* Removes a bucket's retention policy.
*
* @param string $bucketName The name of your Cloud Storage bucket.
* (e.g. 'my-bucket')
*/
function remove_retention_policy(string $bucketName): void
{
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$bucket->reload();
if (array_key_exists('isLocked', $bucket->info()['retentionPolicy']) &&
$bucket->info()['retentionPolicy']['isLocked']) {
printf('Unable to remove retention period as retention policy is locked.' . PHP_EOL);
return;
}
$bucket->update([
'retentionPolicy' => []
]);
printf('Removed bucket %s retention policy' . PHP_EOL, $bucketName);
}Python
fromgoogle.cloudimport storage
defset_retention_policy(bucket_name, retention_period):
"""Defines a retention policy on a given bucket"""
# bucket_name = "my-bucket"
# retention_period = 10
storage_client = storage .Client ()
bucket = storage_client.bucket (bucket_name)
bucket.retention_period = retention_period
bucket.patch()
print(
"Bucket {} retention period set for {} seconds".format(
bucket.name, bucket.retention_period
)
)
fromgoogle.cloudimport storage
defremove_retention_policy(bucket_name):
"""Removes the retention policy on a given bucket"""
# bucket_name = "my-bucket"
storage_client = storage .Client ()
bucket = storage_client.bucket (bucket_name)
bucket.reload()
if bucket.retention_policy_locked :
print(
"Unable to remove retention period as retention policy is locked."
)
return
bucket.retention_period = None
bucket.patch()
print(f"Removed bucket {bucket.name} retention policy")
Ruby
defset_retention_policybucket_name:,retention_period:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# The retention period for objects in bucket
# retention_period = 3600 # 1 hour in seconds
require"google/cloud/storage"
storage=Google::Cloud::Storage .new
bucket=storage.bucketbucket_name
bucket.retention_period =retention_period
puts"Retention period for #{bucket_name} is now #{bucket.retention_period } seconds."
enddefremove_retention_policybucket_name:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
require"google/cloud/storage"
storage=Google::Cloud::Storage .new
bucket=storage.bucketbucket_name
if!bucket.retention_policy_locked?
bucket.retention_period =nil
puts"Retention policy for #{bucket_name} has been removed."
else
puts"Policy is locked and retention policy can't be removed."
end
end
REST APIs
JSON API
Have gcloud CLI installed and initialized, which lets you generate an access token for the
Authorizationheader.Create a JSON file that contains the following information:
{ "retentionPolicy":{ "retentionPeriod":"TIME_IN_SECONDS" } }
Where
TIME_IN_SECONDSis the amount of time in seconds that objects in the bucket must be retained. For example,2678400. See Retention periods for information about how different units of time are measured using seconds.To remove the retention policy from a bucket, use the following in the JSON file:
{ "retentionPolicy":null }
Use
cURLto call the JSON API with aPATCHBucket request:curl -X PATCH --data-binary @JSON_FILE_NAME \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=retentionPolicy"
Where:
JSON_FILE_NAMEis the path for the JSON file that you created in Step 2.BUCKET_NAMEis the name of the relevant bucket. For example,my-bucket.
XML API
The XML API cannot be used to set or remove a retention policy on an existing bucket. It can only be used to include a retention policy with a new bucket.
Lock a bucket
To lock a bucket and permanently restrict edits to the bucket's retention policy:
Console
- In the Google Cloud console, go to the Cloud Storage Buckets page.
In the list of buckets, click the name of the bucket that you want to lock the retention policy for.
Select the Protection tab near the top of the page.
In the Retention policy section, click the Lock button.
The Lock retention policy? dialog box appears.
Read the Permanent notice.
In the Bucket name text box, type in the name of your bucket.
Click Lock policy.
To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, see Troubleshooting.
Command line
Use the gcloud storage buckets update command with the
--lock-retention-period flag:
gcloud storage buckets update gs://BUCKET_NAME --lock-retention-period
Where BUCKET_NAME is the name of the relevant
bucket. For example, my-bucket.
If successful, the response looks similar to the following example:
Updating gs://my-bucket/... Completed 1
Client libraries
For more information, see the
Cloud Storage C++ API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage C# API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage Go API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage Java API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage Node.js API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage PHP API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage Python API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage Ruby API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
C++
namespacegcs=::google::cloud::storage;
using::google::cloud::StatusOr;
[](gcs::Clientclient,std::stringconst&bucket_name){
StatusOr<gcs::BucketMetadata>original=
client.GetBucketMetadata(bucket_name);
if(!original)throwstd::move(original).status();
StatusOr<gcs::BucketMetadata>updated_metadata=
client.LockBucketRetentionPolicy(bucket_name,
original->metageneration());
if(!updated_metadata)throwstd::move(updated_metadata).status();
if(!updated_metadata->has_retention_policy()){
std::cerr << "The bucket " << updated_metadata->name()
<< " does not have a retention policy, even though the"
<< " operation to set it was successful.\n"
<< "This is unexpected, and may indicate that another"
<< " application has modified the bucket concurrently.\n";
return;
}
std::cout << "Retention policy successfully locked for bucket "
<< updated_metadata->name() << "\nNew retention policy is: "
<< updated_metadata->retention_policy()
<< "\nFull metadata: " << *updated_metadata << "\n";
}C#
usingGoogle.Cloud.Storage.V1 ;
usingSystem;
publicclassLockRetentionPolicySample
{
/// <summary>
/// Locks the retention policy of a bucket. This is a one-way process: once a retention
/// policy is locked, it cannot be shortened, removed or unlocked, although it can
/// be increased in duration. The lock persists until the bucket is deleted.
/// </summary>
/// <param name="bucketName">The name of the bucket whose retention policy should be locked.</param>
publicbool?LockRetentionPolicy(stringbucketName="your-unique-bucket-name")
{
varstorage=StorageClient .Create ();
varbucket=storage.GetBucket(bucketName);
storage.LockBucketRetentionPolicy(bucketName,bucket.Metageneration.Value);
bucket=storage.GetBucket(bucketName);
Console.WriteLine($"Retention policy for {bucketName} is now locked");
Console.WriteLine($"Retention policy effective as of {bucket.RetentionPolicy.EffectiveTime}");
returnbucket.RetentionPolicy.IsLocked;
}
}Go
import(
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/storage"
)
// lockRetentionPolicy locks bucket retention policy.
funclockRetentionPolicy(wio.Writer ,bucketNamestring)error{
// bucketName := "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*50)
defercancel()
bucket:=client.Bucket (bucketName)
attrs,err:=bucket.Attrs(ctx)
iferr!=nil{
returnfmt.Errorf("Bucket(%q).Attrs: %w",bucketName,err)
}
conditions:=storage.BucketConditions {
MetagenerationMatch:attrs.MetaGeneration,
}
iferr:=bucket.If(conditions).LockRetentionPolicy (ctx);err!=nil{
returnfmt.Errorf("Bucket(%q).LockRetentionPolicy: %w",bucketName,err)
}
lockedAttrs,err:=bucket.Attrs(ctx)
iferr!=nil{
returnfmt.Errorf("Bucket(%q).Attrs: lockedAttrs: %w",bucketName,err)
}
fmt.Fprintf(w,"Retention policy for %v is now locked\n",bucketName)
fmt.Fprintf(w,"Retention policy effective as of %v\n",lockedAttrs.RetentionPolicy .EffectiveTime)
returnnil
}
Java
importcom.google.cloud.storage.Bucket ;
importcom.google.cloud.storage.Storage ;
importcom.google.cloud.storage.StorageException ;
importcom.google.cloud.storage.StorageOptions ;
importjava.util.Date;
publicclass LockRetentionPolicy{
publicstaticvoidlockRetentionPolicy(StringprojectId,StringbucketName)
throwsStorageException {
// The ID of your GCP project
// String projectId = "your-project-id";
// The ID of your GCS bucket
// String bucketName = "your-unique-bucket-name";
Storage storage=StorageOptions .newBuilder().setProjectId(projectId).build().getService ();
Bucket bucket=
storage.get (bucketName,Storage.BucketGetOption.fields(Storage.BucketField.METAGENERATION));
Bucket lockedBucket=
bucket.lockRetentionPolicy (Storage.BucketTargetOption.metagenerationMatch());
System.out.println("Retention period for "+bucketName+" is now locked");
System.out.println(
"Retention policy effective as of "+newDate(lockedBucket.getRetentionEffectiveTime ()));
}
}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 library
const{Storage}=require('@google-cloud/storage');
// Creates a client
conststorage=newStorage();
asyncfunctionlockRetentionPolicy(){
// Gets the current metageneration value for the bucket, required by
// lock_retention_policy
const[unlockedMetadata]=awaitstorage.bucket(bucketName).getMetadata();
// Warning: Once a retention policy is locked, it cannot be unlocked. The
// retention period can only be increased
const[lockedMetadata]=awaitstorage
.bucket(bucketName)
.lock (unlockedMetadata.metageneration);
console.log(`Retention policy for ${bucketName} is now locked`);
console.log(
`Retention policy effective as of ${lockedMetadata.retentionPolicy .effectiveTime}`
);
returnlockedMetadata;
}
lockRetentionPolicy().catch(console.error);PHP
use Google\Cloud\Storage\StorageClient;
/**
* Locks a bucket's retention policy.
*
* @param string $bucketName The name of your Cloud Storage bucket.
* (e.g. 'my-bucket')
*/
function lock_retention_policy(string $bucketName): void
{
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$bucket->reload();
$bucket->lockRetentionPolicy();
printf('Bucket %s retention policy locked' . PHP_EOL, $bucketName);
}Python
fromgoogle.cloudimport storage
deflock_retention_policy(bucket_name):
"""Locks the retention policy on a given bucket"""
# bucket_name = "my-bucket"
storage_client = storage .Client ()
# get_bucket gets the current metageneration value for the bucket,
# required by lock_retention_policy.
bucket = storage_client.get_bucket (bucket_name)
# Warning: Once a retention policy is locked it cannot be unlocked
# and retention period can only be increased.
bucket.lock_retention_policy ()
print(f"Retention policy for {bucket_name} is now locked")
print(
f"Retention policy effective as of {bucket.retention_policy_effective_time }"
)
Ruby
deflock_retention_policybucket_name:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
require"google/cloud/storage"
storage=Google::Cloud::Storage .new
bucket=storage.bucketbucket_name
# Warning: Once a retention policy is locked it cannot be unlocked
# and retention period can only be increased.
# Uses Bucket#metageneration as a precondition.
bucket.lock_retention_policy!
puts"Retention policy for #{bucket_name} is now locked."
puts"Retention policy effective as of #{bucket.retention_effective_at }."
end
REST APIs
JSON API
Have gcloud CLI installed and initialized, which lets you generate an access token for the
Authorizationheader.Use
cURLto call the JSON API with aPOSTBucket request:curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/lockRetentionPolicy?ifMetagenerationMatch=BUCKET_METAGENERATION_NUMBER"
Where:
BUCKET_NAMEis the name of the relevant bucket. For example,my-bucket.BUCKET_METAGENERATION_NUMBERis the metageneration value for the bucket. For example,8. You can find the metageneration value for your bucket by calling the JSON API with aGETBucket request.
XML API
The XML API cannot be used to lock a bucket. Use one of the other Cloud Storage tools, such as the Google Cloud console, instead.
View a bucket's retention policy and lock status
To view what, if any, retention policy is set on a bucket and whether that retention policy is locked:
Console
- In the Google Cloud console, go to the Cloud Storage Buckets page.
Click the name of the bucket whose status you want to view.
If a bucket has a retention policy, the retention period is displayed in the Protection field for the bucket. If the retention policy is not locked, a lock icon appears next to the retention period in an unlocked state. If the retention policy is locked, a lock icon appears next to the retention period in a locked state.
Command line
Use the gcloud storage buckets describe command with the
--format flag:
gcloud storage buckets describe gs://BUCKET_NAME --format="default(retention_policy)"
Where BUCKET_NAME is the name of the bucket
whose retention policy you want to view. For example, my-bucket.
If successful and a retention policy exists for the bucket, the response is similar to the following:
retention_policy: effectiveTime: '2022-10-04T18:51:22.161000+00:00' retentionPeriod: '129600'
If successful and a retention policy does not exist for the bucket, the response is similar to the following:
null
Client libraries
For more information, see the
Cloud Storage C++ API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage C# API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage Go API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage Java API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage Node.js API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage PHP API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage Python API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
For more information, see the
Cloud Storage Ruby API
reference documentation.
To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see
Set up authentication for client libraries.
C++
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();
if(!bucket_metadata->has_retention_policy()){
std::cout << "The bucket " << bucket_metadata->name()
<< " does not have a retention policy set.\n";
return;
}
std::cout << "The bucket " << bucket_metadata->name()
<< " retention policy is set to "
<< bucket_metadata->retention_policy() << "\n";
}C#
usingGoogle.Cloud.Storage.V1 ;
usingSystem;
usingstaticGoogle.Apis.Storage.v1.Data.Bucket;
publicclassGetRetentionPolicySample
{
publicRetentionPolicyDataGetRetentionPolicy(stringbucketName="your-unique-bucket-name")
{
varstorage=StorageClient .Create ();
varbucket=storage.GetBucket(bucketName);
if(bucket.RetentionPolicy!=null)
{
Console.WriteLine("Retention policy:");
Console.WriteLine($"Period: {bucket.RetentionPolicy.RetentionPeriod}");
Console.WriteLine($"Effective time: {bucket.RetentionPolicy.EffectiveTime}");
boolisLocked=bucket.RetentionPolicy.IsLocked??false;
Console.WriteLine($"Policy locked: {isLocked}");
}
returnbucket.RetentionPolicy;
}
}Go
import(
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/storage"
)
// getRetentionPolicy gets bucket retention policy.
funcgetRetentionPolicy(wio.Writer ,bucketNamestring)(*storage.BucketAttrs ,error){
// bucketName := "bucket-name"
ctx:=context.Background()
client,err:=storage.NewClient(ctx)
iferr!=nil{
returnnil,fmt.Errorf("storage.NewClient: %w",err)
}
deferclient.Close()
ctx,cancel:=context.WithTimeout(ctx,time.Second*10)
defercancel()
attrs,err:=client.Bucket (bucketName).Attrs(ctx)
iferr!=nil{
returnnil,fmt.Errorf("Bucket(%q).Attrs: %w",bucketName,err)
}
ifattrs.RetentionPolicy !=nil{
fmt.Fprintln(w,"Retention Policy")
fmt.Fprintf(w,"period: %v\n",attrs.RetentionPolicy .RetentionPeriod)
fmt.Fprintf(w,"effective time: %v\n",attrs.RetentionPolicy .EffectiveTime)
fmt.Fprintf(w,"policy locked: %v\n",attrs.RetentionPolicy .IsLocked)
}
returnattrs,nil
}
Java
importcom.google.cloud.storage.Bucket ;
importcom.google.cloud.storage.Storage ;
importcom.google.cloud.storage.StorageException ;
importcom.google.cloud.storage.StorageOptions ;
importjava.util.Date;
publicclass GetRetentionPolicy{
publicstaticvoidgetRetentionPolicy(StringprojectId,StringbucketName)
throwsStorageException {
// The ID of your GCP project
// String projectId = "your-project-id";
// The ID of your GCS bucket
// String bucketName = "your-unique-bucket-name";
Storage storage=StorageOptions .newBuilder().setProjectId(projectId).build().getService ();
Bucket bucket=
storage.get (
bucketName,Storage.BucketGetOption.fields(Storage.BucketField.RETENTION_POLICY));
System.out.println("Retention Policy for "+bucketName);
System.out.println("Retention Period: "+bucket.getRetentionPeriod ());
if(bucket.retentionPolicyIsLocked ()!=null && bucket.retentionPolicyIsLocked ()){
System.out.println("Retention Policy is locked");
}
if(bucket.getRetentionEffectiveTime ()!=null){
System.out.println("Effective Time: "+newDate(bucket.getRetentionEffectiveTime ()));
}
}
}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 library
const{Storage}=require('@google-cloud/storage');
// Creates a client
conststorage=newStorage();
asyncfunctiongetRetentionPolicy(){
const[metadata]=awaitstorage.bucket(bucketName).getMetadata();
if(metadata.retentionPolicy ){
constretentionPolicy=metadata.retentionPolicy ;
console.log('A retention policy exists!');
console.log(`Period: ${retentionPolicy .retentionPeriod}`);
console.log(`Effective time: ${retentionPolicy .effectiveTime}`);
if(retentionPolicy .isLocked){
console.log('Policy is locked');
}else{
console.log('Policy is unlocked');
}
}
}
getRetentionPolicy().catch(console.error);PHP
use Google\Cloud\Storage\StorageClient;
/**
* Gets a bucket's retention policy.
*
* @param string $bucketName The name of your Cloud Storage bucket.
* (e.g. 'my-bucket')
*/
function get_retention_policy(string $bucketName): void
{
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$bucket->reload();
printf('Retention Policy for ' . $bucketName . PHP_EOL);
printf('Retention Period: ' . $bucket->info()['retentionPolicy']['retentionPeriod'] . PHP_EOL);
if (array_key_exists('isLocked', $bucket->info()['retentionPolicy']) &&
$bucket->info()['retentionPolicy']['isLocked']) {
printf('Retention Policy is locked' . PHP_EOL);
}
if ($bucket->info()['retentionPolicy']['effectiveTime']) {
printf('Effective Time: ' . $bucket->info()['retentionPolicy']['effectiveTime'] . PHP_EOL);
}
}Python
fromgoogle.cloudimport storage
defget_retention_policy(bucket_name):
"""Gets the retention policy on a given bucket"""
# bucket_name = "my-bucket"
storage_client = storage .Client ()
bucket = storage_client.bucket (bucket_name)
bucket.reload()
print(f"Retention Policy for {bucket_name}")
print(f"Retention Period: {bucket.retention_period }")
if bucket.retention_policy_locked :
print("Retention Policy is locked")
if bucket.retention_policy_effective_time :
print(
f"Effective Time: {bucket.retention_policy_effective_time }"
)
Ruby
defget_retention_policybucket_name:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
require"google/cloud/storage"
storage=Google::Cloud::Storage .new
bucket=storage.bucketbucket_name
puts"Retention policy:"
puts"period: #{bucket.retention_period }"
puts"effective time: #{bucket.retention_effective_at }"
puts"policy locked: #{bucket.retention_policy_locked? }"
end
REST APIs
JSON API
Have gcloud CLI installed and initialized, which lets you generate an access token for the
Authorizationheader.Use
cURLto call the JSON API with aGETBucket request that includes the desiredfields:curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=retentionPolicy"
Where
BUCKET_NAMEis the name of the relevant bucket. For example,my-bucket.If the bucket has a retention policy set on it, the response looks like the following example:
{ "retentionPolicy":{ "retentionPeriod":"TIME_IN_SECONDS", "effectiveTime":"DATETIME", "isLocked":"BOOLEAN" }, }
XML API
The XML API cannot be used to view the retention policy on a bucket. Use one of the other Cloud Storage tools, such as the Google Cloud console, instead.
What's next
- Learn more about retention policies.
- Learn how to use object holds.
- Learn about Object Lifecycle Management, which can automatically delete files once they reach their retention period.