Manage object lifecycles Stay organized with collections Save and categorize content based on your preferences.
This page describes how to set Object Lifecycle Management on a bucket and howto view a bucket's current lifecycle configuration. Lifecycle configurationsapply to all current and future objects in the bucket.
Required roles
To get the permissions that you need to set and manage Object LifecycleManagement for a bucket, ask your administrator to grant you the Storage Admin(roles/storage.admin) role on the bucket. Thispredefined role containsthe permissions required to set and manage Object Lifecycle Management for abucket. To see the exact permissions required, expand theRequired permissions section:
Required permissions
storage.buckets.getstorage.buckets.list- This permission is only required if you plan on using theGoogle Cloud console to perform the instructions on this page.
storage.buckets.update
You might also be able to get these permissions withcustom roles.
For information about granting roles on buckets, seeSet and manage IAM policies on buckets.
Set the lifecycle configuration for a bucket
Warning: When you change your lifecycle configuration, Object LifecycleManagement may still perform actions based on the old configuration for up to 24hours. For example, if you change anAge condition from 10 days to 20 days,an object that is 11 days old could be deleted by Object Lifecycle Managementup to 24 hours later, based on the old configuration.Console
- In the Google Cloud console, go to the Cloud StorageBuckets page.
In the bucket list, find the bucket you want to enable, and clickthe bucket's name.
Click theLifecycle tab.
The lifecycle rules page appears. From here you can edit ordeleteexisting rules. To add a new rule:
ClickAdd a rule.
In the page that appears, specify a configuration.
Select theaction to take when an object meets the conditions.
ClickContinue.
Select theconditions under which an action is taken.
ClickContinue.
ClickCreate.
To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, seeTroubleshooting.
Command line
Create a JSON file with thelifecycle configuration rules youwould like to apply. Seeconfiguration examples for sampleJSON files.
Use the
gcloud storage buckets updatecommand with the--lifecycle-fileflag:gcloud storage buckets update gs://BUCKET_NAME --lifecycle-file=LIFECYCLE_CONFIG_FILE
Where:
BUCKET_NAMEis the name of the relevantbucket. For example,my-bucket.LIFECYCLE_CONFIG_FILEis the path for theJSON file that you created in Step 1.
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. The following sample sets a lifecycle configuration on a bucket: The following sample removes any existing lifecycle configuration from a bucket: 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. The following sample sets a lifecycle configuration on a bucket: The following sample removes any existing lifecycle configuration from a bucket: 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. The following sample sets a lifecycle configuration on a bucket: The following sample removes any existing lifecycle configuration from a bucket: 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. The following sample sets a lifecycle configuration on a bucket: The following sample removes any existing lifecycle configuration from a bucket: 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. The following sample sets a lifecycle configuration on a bucket: The following sample removes any existing lifecycle configuration from a bucket: 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. The following sample sets a lifecycle configuration on a bucket: The following sample removes any existing lifecycle configuration from a bucket: 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. The following sample sets a lifecycle configuration on a bucket: The following sample removes any existing lifecycle configuration from a bucket: 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. The following sample sets a lifecycle configuration on a bucket: The following sample removes any existing lifecycle configuration from a bucket:C++
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name){gcs::BucketLifecyclebucket_lifecycle_rules=gcs::BucketLifecycle{{gcs::LifecycleRule(gcs::LifecycleRule::ConditionConjunction(gcs::LifecycleRule::MaxAge(30),gcs::LifecycleRule::IsLive(true)),gcs::LifecycleRule::Delete())}};StatusOr<gcs::BucketMetadata>updated_metadata=client.PatchBucket(bucket_name,gcs::BucketMetadataPatchBuilder().SetLifecycle(bucket_lifecycle_rules));if(!updated_metadata)throwstd::move(updated_metadata).status();if(!updated_metadata->has_lifecycle()||updated_metadata->lifecycle().rule.empty()){std::cout <<"Bucket lifecycle management is not enabled for bucket " <<updated_metadata->name() <<".\n";return;}std::cout <<"Successfully enabled bucket lifecycle management for bucket " <<updated_metadata->name() <<".\n";std::cout <<"The bucket lifecycle rules are";for(autoconst&kv:updated_metadata->lifecycle().rule){std::cout <<"\n " <<kv.condition() <<", " <<kv.action();}std::cout <<"\n";}namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name){StatusOr<gcs::BucketMetadata>updated_metadata=client.PatchBucket(bucket_name,gcs::BucketMetadataPatchBuilder().ResetLifecycle());if(!updated_metadata)throwstd::move(updated_metadata).status();std::cout <<"Successfully disabled bucket lifecycle management for bucket " <<updated_metadata->name() <<".\n";}C#
usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;usingSystem.Collections.Generic;publicclassEnableBucketLifecycleManagementSample{publicBucketEnableBucketLifecycleManagement(stringbucketName="your-unique-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName);bucket.Lifecycle=newBucket.LifecycleData{Rule=newList<Bucket.LifecycleData.RuleData>{newBucket.LifecycleData.RuleData{Condition=newBucket.LifecycleData.RuleData.ConditionData{Age=100},Action=newBucket.LifecycleData.RuleData.ActionData{Type="Delete"}}}};bucket=storage.UpdateBucket(bucket);Console.WriteLine($"Lifecycle management is enabled for bucket {bucketName} and the rules are:");foreach(varruleinbucket.Lifecycle.Rule){Console.WriteLine("Action:");Console.WriteLine($"Type: {rule.Action.Type}");Console.WriteLine($"Storage Class: {rule.Action.StorageClass}");Console.WriteLine("Condition:");Console.WriteLine($"Age: \t{rule.Condition.Age}");Console.WriteLine($"Created Before: \t{rule.Condition.CreatedBefore}");Console.WriteLine($"Time Before: \t{rule.Condition.CustomTimeBefore}");Console.WriteLine($"Days Since Custom Time: \t{rule.Condition.DaysSinceCustomTime}");Console.WriteLine($"Days Since Non-current Time: \t{rule.Condition.DaysSinceNoncurrentTime}");Console.WriteLine($"IsLive: \t{rule.Condition.IsLive}");Console.WriteLine($"Storage Class: \t{rule.Condition.MatchesStorageClass}");Console.WriteLine($"Noncurrent Time Before: \t{rule.Condition.NoncurrentTimeBefore}");Console.WriteLine($"Newer Versions: \t{rule.Condition.NumNewerVersions}");}returnbucket;}}usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassDisableBucketLifecycleManagementSample{publicBucketDisableBucketLifecycleManagement(stringbucketName="your-unique-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName);bucket.Lifecycle=null;bucket=storage.UpdateBucket(bucket);Console.WriteLine($"Lifecycle management is disabled for bucket {bucketName}.");returnbucket;}}Go
import("context""fmt""io""time""cloud.google.com/go/storage")// enableBucketLifecycleManagement adds a lifecycle delete rule with the// condition that the object is 100 days old.funcenableBucketLifecycleManagement(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*10)defercancel()bucket:=client.Bucket(bucketName)bucketAttrsToUpdate:=storage.BucketAttrsToUpdate{Lifecycle:&storage.Lifecycle{Rules:[]storage.LifecycleRule{{Action:storage.LifecycleAction{Type:"Delete"},Condition:storage.LifecycleCondition{AgeInDays:100,},},},},}attrs,err:=bucket.Update(ctx,bucketAttrsToUpdate)iferr!=nil{returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)}fmt.Fprintf(w,"Lifecycle management is enabled for bucket %v\n and the rules are:\n",bucketName)for_,rule:=rangeattrs.Lifecycle.Rules{fmt.Fprintf(w,"Action: %v\n",rule.Action)fmt.Fprintf(w,"Condition: %v\n",rule.Condition)}returnnil}import("context""fmt""io""time""cloud.google.com/go/storage")// disableBucketLifecycleManagement removes all existing lifecycle rules// from the bucket.funcdisableBucketLifecycleManagement(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*10)defercancel()bucket:=client.Bucket(bucketName)bucketAttrsToUpdate:=storage.BucketAttrsToUpdate{Lifecycle:&storage.Lifecycle{},}_,err=bucket.Update(ctx,bucketAttrsToUpdate)iferr!=nil{returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)}fmt.Fprintf(w,"Lifecycle management is disabled for bucket %v.\n",bucketName)returnnil}Java
import staticcom.google.cloud.storage.BucketInfo.LifecycleRule.LifecycleAction;import staticcom.google.cloud.storage.BucketInfo.LifecycleRule.LifecycleCondition;importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.BucketInfo.LifecycleRule;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importcom.google.common.collect.ImmutableList;publicclassEnableLifecycleManagement{publicstaticvoidenableLifecycleManagement(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);// See the LifecycleRule documentation for additional info on what you can do with lifecycle// management rules. This one deletes objects that are over 100 days old.// https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/BucketInfo.LifecycleRule.htmlbucket.toBuilder().setLifecycleRules(ImmutableList.of(newLifecycleRule(LifecycleAction.newDeleteAction(),LifecycleCondition.newBuilder().setAge(100).build()))).build().update();System.out.println("Lifecycle management was enabled and configured for bucket "+bucketName);}}importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.Storage.BucketTargetOption;importcom.google.cloud.storage.StorageOptions;publicclassDisableLifecycleManagement{publicstaticvoiddisableLifecycleManagement(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();// first look up the bucket, so we will have its metagenerationBucketbucket=storage.get(bucketName);storage.update(bucket.toBuilder().deleteLifecycleRules().build(),BucketTargetOption.metagenerationMatch());System.out.println("Lifecycle management was disabled for bucket "+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';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionenableBucketLifecycleManagement(){const[metadata]=awaitstorage.bucket(bucketName).addLifecycleRule({action:{type:'Delete',},condition:{age:100},});console.log(`Lifecycle management is enabled for bucket${bucketName} and the rules are:`);console.log(metadata.lifecycle.rule);}enableBucketLifecycleManagement().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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiondisableBucketLifecycleManagement(){awaitstorage.bucket(bucketName).setMetadata({lifecycle:null});console.log(`Lifecycle management is disabled for bucket${bucketName}`);}disableBucketLifecycleManagement().catch(console.error);PHP
use Google\Cloud\Storage\StorageClient;use Google\Cloud\Storage\Bucket;/** * Enable bucket lifecycle management. * * @param string $bucketName The name of your Cloud Storage bucket. * (e.g. 'my-bucket') */function enable_bucket_lifecycle_management(string $bucketName): void{ $storage = new StorageClient(); $bucket = $storage->bucket($bucketName); $lifecycle = Bucket::lifecycle() ->addDeleteRule([ 'age' => 100 ]); $bucket->update([ 'lifecycle' => $lifecycle ]); $lifecycle = $bucket->currentLifecycle(); printf('Lifecycle management is enabled for bucket %s and the rules are:' . PHP_EOL, $bucketName); foreach ($lifecycle as $rule) { print_r($rule); print(PHP_EOL); }}use Google\Cloud\Storage\StorageClient;/** * Disable bucket lifecycle management. * * @param string $bucketName The name of your Cloud Storage bucket. * (e.g. 'my-bucket') */function disable_bucket_lifecycle_management(string $bucketName): void{ $storage = new StorageClient(); $bucket = $storage->bucket($bucketName); $bucket->update([ 'lifecycle' => null ]); printf('Lifecycle management is disabled for bucket %s.' . PHP_EOL, $bucketName);}Python
fromgoogle.cloudimportstoragedefenable_bucket_lifecycle_management(bucket_name):"""Enable lifecycle management for a bucket"""# bucket_name = "my-bucket"storage_client=storage.Client()bucket=storage_client.get_bucket(bucket_name)rules=bucket.lifecycle_rulesprint(f"Lifecycle management rules for bucket{bucket_name} are{list(rules)}")bucket.add_lifecycle_delete_rule(age=2)bucket.patch()rules=bucket.lifecycle_rulesprint(f"Lifecycle management is enable for bucket{bucket_name} and the rules are{list(rules)}")returnbucketfromgoogle.cloudimportstoragedefdisable_bucket_lifecycle_management(bucket_name):"""Disable lifecycle management for a bucket"""# bucket_name = "my-bucket"storage_client=storage.Client()bucket=storage_client.get_bucket(bucket_name)bucket.clear_lifecyle_rules()bucket.patch()rules=bucket.lifecycle_rulesprint(f"Lifecycle management is disable for bucket{bucket_name} and the rules are{list(rules)}")returnbucketRuby
defenable_bucket_lifecycle_managementbucket_name:# Enable lifecycle management for a bucket# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namerules=bucket.lifecycledo|l|l.add_delete_ruleage:2endputs"Lifecycle management is enabled for bucket#{bucket_name} and the rules are#{rules}"enddefdisable_bucket_lifecycle_managementbucket_name:# Disable lifecycle management for a bucket# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.lifecycledo|l|l.clearendputs"Lifecycle management is disabled for bucket#{bucket_name}"end
Terraform
You can use aTerraform resource to set a lifecycleconfiguration for a bucket managed by Terraform. To set a lifecycleconfiguration on an existing bucket that isn't yet managed by Terraform,you must firstimport the existing bucket.
To find out whether a lifecycle condition is supported by Terraform, see theTerraform documentation for thecondition block.
resource "random_id" "bucket_prefix" { byte_length = 8}resource "google_storage_bucket" "auto_expire" { provider = google-beta name = "${random_id.bucket_prefix.hex}-example-bucket" location = "US" lifecycle_rule { condition { age = 3 } action { type = "Delete" } }}REST APIs
JSON API
Have gcloud CLIinstalled and initialized, which lets you generate an access token for the
Authorizationheader.Create a JSON file with thelifecycle configuration rules youwould like to apply. Seeconfiguration examples for sampleJSON files.
Use
cURLto call theJSON API with aPATCHBucket request:curl -X PATCH --data-binary @LIFECYCLE_CONFIG_FILE \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=lifecycle"
Where:
LIFECYCLE_CONFIG_FILEis the path for theJSON file that you created in Step 2.BUCKET_NAMEis the name of the relevantbucket. For example,my-bucket.
XML API
Have gcloud CLIinstalled and initialized, which lets you generate an access token for the
Authorizationheader.Create an XML file with thelifecycle configuration rulesyou would like to apply. Seeconfiguration examples for sampleXML files.
Use
cURLto call theXML API with aPUTBucket request andlifecyclequery string parameter:curl -X PUT --data-binary @XML_FILE_NAME \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/BUCKET_NAME?lifecycle"
Where:
XML_FILE_NAMEis the path for the XMLfile that you created in Step 2.BUCKET_NAMEis the name of the relevantbucket. For example,my-bucket.
Check the lifecycle configuration for a bucket
Console
- In the Google Cloud console, go to the Cloud StorageBuckets page.
In the bucket list, the lifecycle status of each bucket is foundin theLifecycle column.
You can click this status to add, view, edit, and delete rules.
To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, seeTroubleshooting.
Command line
Use thegcloud storage buckets describe command with the--format flag:
gcloud storage buckets describe gs://BUCKET_NAME --format="default(lifecycle_config)"
WhereBUCKET_NAME is the name of the bucketwhose lifecycle configuration you want to view. For example,my-bucket.
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&bucket_name){StatusOr<gcs::BucketMetadata>updated_metadata=client.GetBucketMetadata(bucket_name);if(!updated_metadata)throwstd::move(updated_metadata).status();if(!updated_metadata->has_lifecycle()||updated_metadata->lifecycle().rule.empty()){std::cout <<"Bucket lifecycle management is not enabled for bucket " <<updated_metadata->name() <<".\n";return;}std::cout <<"Bucket lifecycle management is enabled for bucket " <<updated_metadata->name() <<".\n";std::cout <<"The bucket lifecycle rules are";for(autoconst&kv:updated_metadata->lifecycle().rule){std::cout <<"\n " <<kv.condition() <<", " <<kv.action();}std::cout <<"\n";}C#
usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassGetBucketMetadataSample{publicBucketGetBucketMetadata(stringbucketName="your-unique-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName,newGetBucketOptions{Projection=Projection.Full});Console.WriteLine($"Bucket:\t{bucket.Name}");Console.WriteLine($"Acl:\t{bucket.Acl}");Console.WriteLine($"Billing:\t{bucket.Billing}");Console.WriteLine($"Cors:\t{bucket.Cors}");Console.WriteLine($"DefaultEventBasedHold:\t{bucket.DefaultEventBasedHold}");Console.WriteLine($"DefaultObjectAcl:\t{bucket.DefaultObjectAcl}");Console.WriteLine($"Encryption:\t{bucket.Encryption}");if(bucket.Encryption!=null){Console.WriteLine($"KmsKeyName:\t{bucket.Encryption.DefaultKmsKeyName}");}Console.WriteLine($"Id:\t{bucket.Id}");Console.WriteLine($"Kind:\t{bucket.Kind}");Console.WriteLine($"Lifecycle:\t{bucket.Lifecycle}");Console.WriteLine($"Location:\t{bucket.Location}");Console.WriteLine($"LocationType:\t{bucket.LocationType}");Console.WriteLine($"Logging:\t{bucket.Logging}");Console.WriteLine($"Metageneration:\t{bucket.Metageneration}");Console.WriteLine($"ObjectRetention:\t{bucket.ObjectRetention}");Console.WriteLine($"Owner:\t{bucket.Owner}");Console.WriteLine($"ProjectNumber:\t{bucket.ProjectNumber}");Console.WriteLine($"RetentionPolicy:\t{bucket.RetentionPolicy}");Console.WriteLine($"SelfLink:\t{bucket.SelfLink}");Console.WriteLine($"StorageClass:\t{bucket.StorageClass}");Console.WriteLine($"TimeCreated:\t{bucket.TimeCreated}");Console.WriteLine($"Updated:\t{bucket.Updated}");Console.WriteLine($"Versioning:\t{bucket.Versioning}");Console.WriteLine($"Website:\t{bucket.Website}");Console.WriteLine($"TurboReplication:\t{bucket.Rpo}");if(bucket.Labels!=null){Console.WriteLine("Labels:");foreach(varlabelinbucket.Labels){Console.WriteLine($"{label.Key}:\t{label.Value}");}}returnbucket;}}Go
import("context""fmt""io""time""cloud.google.com/go/storage")// getBucketMetadata gets the bucket metadata.funcgetBucketMetadata(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)}fmt.Fprintf(w,"BucketName: %v\n",attrs.Name)fmt.Fprintf(w,"Location: %v\n",attrs.Location)fmt.Fprintf(w,"LocationType: %v\n",attrs.LocationType)fmt.Fprintf(w,"StorageClass: %v\n",attrs.StorageClass)fmt.Fprintf(w,"Turbo replication (RPO): %v\n",attrs.RPO)fmt.Fprintf(w,"TimeCreated: %v\n",attrs.Created)fmt.Fprintf(w,"Metageneration: %v\n",attrs.MetaGeneration)fmt.Fprintf(w,"PredefinedACL: %v\n",attrs.PredefinedACL)ifattrs.Encryption!=nil{fmt.Fprintf(w,"DefaultKmsKeyName: %v\n",attrs.Encryption.DefaultKMSKeyName)}ifattrs.Website!=nil{fmt.Fprintf(w,"IndexPage: %v\n",attrs.Website.MainPageSuffix)fmt.Fprintf(w,"NotFoundPage: %v\n",attrs.Website.NotFoundPage)}fmt.Fprintf(w,"DefaultEventBasedHold: %v\n",attrs.DefaultEventBasedHold)ifattrs.RetentionPolicy!=nil{fmt.Fprintf(w,"RetentionEffectiveTime: %v\n",attrs.RetentionPolicy.EffectiveTime)fmt.Fprintf(w,"RetentionPeriod: %v\n",attrs.RetentionPolicy.RetentionPeriod)fmt.Fprintf(w,"RetentionPolicyIsLocked: %v\n",attrs.RetentionPolicy.IsLocked)}fmt.Fprintf(w,"ObjectRetentionMode: %v\n",attrs.ObjectRetentionMode)fmt.Fprintf(w,"RequesterPays: %v\n",attrs.RequesterPays)fmt.Fprintf(w,"VersioningEnabled: %v\n",attrs.VersioningEnabled)ifattrs.Logging!=nil{fmt.Fprintf(w,"LogBucket: %v\n",attrs.Logging.LogBucket)fmt.Fprintf(w,"LogObjectPrefix: %v\n",attrs.Logging.LogObjectPrefix)}ifattrs.CORS!=nil{fmt.Fprintln(w,"CORS:")for_,v:=rangeattrs.CORS{fmt.Fprintf(w,"\tMaxAge: %v\n",v.MaxAge)fmt.Fprintf(w,"\tMethods: %v\n",v.Methods)fmt.Fprintf(w,"\tOrigins: %v\n",v.Origins)fmt.Fprintf(w,"\tResponseHeaders: %v\n",v.ResponseHeaders)}}ifattrs.Labels!=nil{fmt.Fprintf(w,"\n\n\nLabels:")forkey,value:=rangeattrs.Labels{fmt.Fprintf(w,"\t%v = %v\n",key,value)}}returnattrs,nil}Java
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);}}}}Node.js
// 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));}PHP
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));}Python
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}")Ruby
defget_bucket_metadatabucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_nameputs"ID:#{bucket.id}"puts"Name:#{bucket.name}"puts"Storage Class:#{bucket.storage_class}"puts"Location:#{bucket.location}"puts"Location Type:#{bucket.location_type}"puts"Cors:#{bucket.cors}"puts"Default Event Based Hold:#{bucket.default_event_based_hold?}"puts"Default KMS Key Name:#{bucket.default_kms_key}"puts"Logging Bucket:#{bucket.logging_bucket}"puts"Logging Prefix:#{bucket.logging_prefix}"puts"Metageneration:#{bucket.metageneration}"puts"Retention Effective Time:#{bucket.retention_effective_at}"puts"Retention Period:#{bucket.retention_period}"puts"Retention Policy Locked:#{bucket.retention_policy_locked?}"puts"Requester Pays:#{bucket.requester_pays}"puts"Self Link:#{bucket.api_url}"puts"Time Created:#{bucket.created_at}"puts"Versioning Enabled:#{bucket.versioning?}"puts"Index Page:#{bucket.website_main}"puts"Not Found Page:#{bucket.website_404}"puts"Labels:"bucket.labels.eachdo|key,value|puts" -#{key} =#{value}"endputs"Lifecycle Rules:"bucket.lifecycle.eachdo|rule|puts"#{rule.action} -#{rule.storage_class} -#{rule.age} -#{rule.matches_storage_class}"endend
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 aGETBucket request:curl -X GET \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=lifecycle"
Where
BUCKET_NAMEis the name of therelevant bucket. For example,my-bucket.
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 and alifecyclequery string parameter:curl -X GET \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/BUCKET_NAME?lifecycle"
Where
BUCKET_NAMEis the name of therelevant bucket. For example,my-bucket.
What's next
- Learn more aboutObject Lifecycle Management, including the availablelifecycle actions and lifecycle conditions.
- Explorelifecycle configuration examples.
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 2026-02-19 UTC.