Using bucket labels
Stay organized with collections
Save and categorize content based on your preferences.
This page shows you how to add, modify, remove, and view the labels set on a bucket in Cloud Storage.
Required roles
In order to get the required permissions for adding and managing bucket labels,
ask your administrator to grant you the Storage Admin
(roles/storage.admin) IAM role on the bucket.
This predefined role contains the permissions required to add and manage bucket labels. To see the exact permissions that are 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 instructions on granting roles on buckets, see Set and manage IAM policies on buckets.
Add, modify, or remove a bucket's labels
Console
- In the Google Cloud console, go to the Cloud Storage Buckets page.
In the list of buckets, click the name of the bucket for which you want to add, modify, or remove labels.
In the Bucket details page, click the Configuration tab.
Click the Edit icon (edit) for Labels.
The label editor window appears.
To add a label, click the add_box Add label button, and specify a
keyand avaluefor your label.To modify an existing label, click its Value and a enter a new value.
To remove a label, click the Trash icon associated with the label you want to remove.
Click Save.
To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, see Troubleshooting.
Command line
To add a new label or update an existing label, use the
gcloud storage buckets update command with the --update-labels
flag. For example:
gcloud storage buckets update gs://BUCKET_NAME --update-labels=KEY_1=VALUE_1
Where
BUCKET_NAMEis the name of the bucket that the label applies to. For example,my-bucket.KEY_1is the key name for your label. For example,pet.VALUE_1is the value for your label. For example,dog.
To remove an existing label, use the -remove-labels flag. For example:
gcloud storage buckets update gs://BUCKET_NAME --remove-labels=KEY_1
You can change multiple labels using the previous commands by including the
labels in a comma-separated list within the relevant flag. For example,
--update-labels=blue-key=cyan,red-key=ruby.
To remove all labels attached to a bucket, use the following command:
gcloud storage buckets update gs://BUCKET_NAME --clear-labels
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 adds the specified label to a bucket, or modifies the label if it already exists for the bucket: The following sample removes the specified label 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 adds the specified label to a bucket, or modifies the label if it already exists for the bucket: The following sample removes the specified label 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 adds the specified label to a bucket, or modifies the label if it already exists for the bucket: The following sample removes the specified label 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 adds the specified label to a bucket, or modifies the label if it already exists for the bucket: The following sample removes the specified label 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 adds the specified label to a bucket, or modifies the label if it already exists for the bucket: The following sample removes the specified label 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 adds the specified label to a bucket, or modifies the label if it already exists for the bucket: The following sample removes the specified label 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 adds the specified label to a bucket, or modifies the label if it already exists for the bucket: The following sample removes the specified label 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 adds the specified label to a bucket, or modifies the label if it already exists for the bucket: The following sample removes the specified label from a bucket:C++
namespacegcs=::google::cloud::storage;
using::google::cloud::StatusOr;
[](gcs::Clientclient,std::stringconst&bucket_name,
std::stringconst&label_key,std::stringconst&label_value){
StatusOr<gcs::BucketMetadata>updated=client.PatchBucket(
bucket_name,
gcs::BucketMetadataPatchBuilder().SetLabel(label_key,label_value));
if(!updated)throwstd::move(updated).status();
std::cout << "Successfully set label " << label_key << " to " << label_value
<< " on bucket " << updated->name() << ".";
std::cout << " The bucket labels are now:";
for(autoconst&kv:updated->labels()){
std::cout << "\n " << kv.first << ": " << kv.second;
}
std::cout << "\n";
}namespacegcs=::google::cloud::storage;
using::google::cloud::StatusOr;
[](gcs::Clientclient,std::stringconst&bucket_name,
std::stringconst&label_key){
StatusOr<gcs::BucketMetadata>updated=client.PatchBucket(
bucket_name,gcs::BucketMetadataPatchBuilder().ResetLabel(label_key));
if(!updated)throwstd::move(updated).status();
std::cout << "Successfully reset label " << label_key << " on bucket "
<< updated->name() << ".";
if(updated->labels().empty()){
std::cout << " The bucket now has no labels.\n";
return;
}
std::cout << " The bucket labels are now:";
for(autoconst&kv:updated->labels()){
std::cout << "\n " << kv.first << ": " << kv.second;
}
std::cout << "\n";
}C#
usingGoogle.Apis.Storage.v1.Data;
usingGoogle.Cloud.Storage.V1 ;
usingSystem;
usingSystem.Collections.Generic;
publicclassBucketAddLabelSample
{
publicBucketBucketAddLabel(
stringbucketName="your-bucket-name",
stringlabelKey="label-key-to-add",
stringlabelValue="label-value-to-add")
{
varstorage=StorageClient .Create ();
varbucket=storage.GetBucket(bucketName);
if(bucket.Labels==null)
{
bucket.Labels=newDictionary<string,string>();
}
bucket.Labels.Add(labelKey,labelValue);
bucket=storage.UpdateBucket(bucket);
Console.WriteLine($"Added label {labelKey} with value {labelValue} to bucket {bucketName}.");
returnbucket;
}
}
usingGoogle.Apis.Storage.v1.Data;
usingGoogle.Cloud.Storage.V1 ;
usingSystem;
publicclassBucketRemoveLabelSample
{
publicBucketBucketRemoveLabel(stringbucketName="your-bucket-name",stringlabelKey="label-key-to-remove")
{
varstorage=StorageClient .Create ();
varbucket=storage.GetBucket(bucketName);
if(bucket.Labels!=null && bucket.Labels.Keys.Contains(labelKey))
{
bucket.Labels.Remove(labelKey);
bucket=storage.UpdateBucket(bucket);
Console.WriteLine($"Removed label {labelKey} from bucket {bucketName}.");
}
else
{
Console.WriteLine($"No such label available on {bucketName}.");
}
returnbucket;
}
}Go
import(
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/storage"
)
// addBucketLabel adds a label on a bucket.
funcaddBucketLabel(wio.Writer ,bucketName,labelName,labelValuestring)error{
// bucketName := "bucket-name"
// labelName := "label-name"
// labelValue := "label-value"
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 {}
bucketAttrsToUpdate.SetLabel (labelName,labelValue)
if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{
returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)
}
fmt.Fprintf(w,"Added label %q with value %q to bucket %v\n",labelName,labelValue,bucketName)
returnnil
}
import(
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/storage"
)
// removeBucketLabel removes a label on a bucket.
funcremoveBucketLabel(wio.Writer ,bucketName,labelNamestring)error{
// bucketName := "bucket-name"
// labelName := "label-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 {}
bucketAttrsToUpdate.DeleteLabel (labelName)
if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{
returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)
}
fmt.Fprintf(w,"Removed label %q from bucket %v\n",labelName,bucketName)
returnnil
}
Java
importcom.google.cloud.storage.Bucket ;
importcom.google.cloud.storage.Storage ;
importcom.google.cloud.storage.StorageOptions ;
importjava.util.HashMap;
importjava.util.Map;
publicclass AddBucketLabel{
publicstaticvoidaddBucketLabel(
StringprojectId,StringbucketName,StringlabelKey,StringlabelValue){
// The ID of your GCP project
// String projectId = "your-project-id";
// The ID of your GCS bucket
// String bucketName = "your-unique-bucket-name";
// The key of the label to add
// String labelKey = "label-key-to-add";
// The value of the label to add
// String labelValue = "label-value-to-add";
Map<String,String>newLabels=newHashMap<>();
newLabels.put(labelKey,labelValue);
Storage storage=StorageOptions .newBuilder().setProjectId(projectId).build().getService ();
Bucket bucket=storage.get (bucketName);
Map<String,String>labels=bucket.getLabels();
if(labels!=null){
newLabels.putAll(labels);
}
bucket.toBuilder ().setLabels(newLabels).build().update();
System.out.println(
"Added label "+labelKey+" with value "+labelValue+" to bucket "+bucketName+".");
}
}
importcom.google.cloud.storage.Bucket ;
importcom.google.cloud.storage.Storage ;
importcom.google.cloud.storage.StorageOptions ;
importjava.util.HashMap;
importjava.util.Map;
publicclass RemoveBucketLabel{
publicstaticvoidremoveBucketLabel(StringprojectId,StringbucketName,StringlabelKey){
// The ID of your GCP project
// String projectId = "your-project-id";
// The ID of your GCS bucket
// String bucketName = "your-unique-bucket-name";
// The key of the label to remove from the bucket
// String labelKey = "label-key-to-remove";
Storage storage=StorageOptions .newBuilder().setProjectId(projectId).build().getService ();
Map<String,String>labelsToRemove=newHashMap<>();
labelsToRemove.put(labelKey,null);
Bucket bucket=storage.get (bucketName);
Map<String,String>labels;
if(bucket.getLabels()==null){
labels=newHashMap<>();
}else{
labels=newHashMap(bucket.getLabels());
}
labels.putAll(labelsToRemove);
bucket.toBuilder ().setLabels(labels).build().update();
System.out.println("Removed label "+labelKey+" from 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';
// The key of the label to add
// const labelKey = 'label-key-to-add';
// The value of the label to add
// const labelValue = 'label-value-to-add';
// Imports the Google Cloud client library
const{Storage}=require('@google-cloud/storage');
// Creates a client
conststorage=newStorage();
constlabels={
[labelKey]:labelValue,
};
asyncfunctionaddBucketLabel(){
awaitstorage.bucket(bucketName).setMetadata({labels});
console.log(`Added label to bucket ${bucketName}`);
}
addBucketLabel().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';
// The key of the label to remove from the bucket
// const labelKey = 'label-key-to-remove';
// Imports the Google Cloud client library
const{Storage}=require('@google-cloud/storage');
// Creates a client
conststorage=newStorage();
asyncfunctionremoveBucketLabel(){
constlabels={};
// To remove a label set the value of the key to null.
labels[labelKey]=null;
awaitstorage.bucket(bucketName).setMetadata({labels});
console.log(`Removed labels from bucket ${bucketName}`);
}
removeBucketLabel().catch(console.error);PHP
use Google\Cloud\Storage\StorageClient;
/**
* Adds or updates a bucket label.
*
* @param string $bucketName The name of your Cloud Storage bucket.
* (e.g. 'my-bucket')
* @param string $labelName The name of the label to add.
* (e.g. 'label-key-to-add')
* @param string $labelValue The value of the label to add.
* (e.g. 'label-value-to-add')
*/
function add_bucket_label(string $bucketName, string $labelName, string $labelValue): void
{
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$newLabels = [$labelName => $labelValue];
$bucket->update(['labels' => $newLabels]);
printf('Added label %s (%s) to %s' . PHP_EOL, $labelName, $labelValue, $bucketName);
}use Google\Cloud\Storage\StorageClient;
/**
* Removes a label from a bucket.
*
* @param string $bucketName The name of your Cloud Storage bucket.
* (e.g. 'my-bucket')
* @param string $labelName The name of the label to remove.
* (e.g. 'label-key-to-remove')
*/
function remove_bucket_label(string $bucketName, string $labelName): void
{
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$labels = [$labelName => null];
$bucket->update(['labels' => $labels]);
printf('Removed label %s from %s' . PHP_EOL, $labelName, $bucketName);
}Python
importpprint
fromgoogle.cloudimport storage
defadd_bucket_label(bucket_name):
"""Add a label to a bucket."""
# bucket_name = "your-bucket-name"
storage_client = storage .Client ()
bucket = storage_client.get_bucket (bucket_name)
labels = bucket.labels
labels["example"] = "label"
bucket.labels = labels
bucket.patch()
print(f"Updated labels on {bucket.name}.")
pprint.pprint(bucket.labels )
importpprint
fromgoogle.cloudimport storage
defremove_bucket_label(bucket_name):
"""Remove a label from a bucket."""
# bucket_name = "your-bucket-name"
storage_client = storage .Client ()
bucket = storage_client.get_bucket (bucket_name)
labels = bucket.labels
if "example" in labels:
del labels["example"]
bucket.labels = labels
bucket.patch()
print(f"Removed labels on {bucket.name}.")
pprint.pprint(bucket.labels )
Ruby
defadd_bucket_labelbucket_name:,label_key:,label_value:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# The key of the label to add
# label_key = "label-key-to-add"
# The value of the label to add
# label_value = "label-value-to-add"
require"google/cloud/storage"
storage=Google::Cloud::Storage .new
bucket=storage.bucketbucket_name
bucket.updatedo|bucket|
bucket.labels[label_key]=label_value
end
puts"Added label #{label_key} with value #{label_value} to #{bucket_name}"
enddefremove_bucket_labelbucket_name:,label_key:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# The key of the label to remove from the bucket
# label_key = "label-key-to-remove"
require"google/cloud/storage"
storage=Google::Cloud::Storage .new
bucket=storage.bucketbucket_name
bucket.updatedo|bucket|
bucket.labels[label_key]=nil
end
puts"Deleted label #{label_key} from #{bucket_name}"
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:
{ "labels":{ "KEY_1":"VALUE_1" } }
Where
KEY_1is the key name for your label. For example,pet.VALUE_1is the value for your label. For example,dog. If you want to remove a key, usenullin place of"<var>VALUE_1</var>".
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=labels"
Where:
JSON_FILE_NAMEis the path for the JSON file that you created in Step 2.BUCKET_NAMEis the name of the bucket that the label applies to. For example,my-bucket.
You can add, edit, or remove multiple key:value pairs in a request.
XML API
Have gcloud CLI installed and initialized, which lets you generate an access token for the
Authorizationheader.Create an XML file that contains the following information:
<Tagging> <TagSet> <Tag> <Key>KEY_1</Key> <Value>VALUE_1</Value> </Tag> </TagSet> </Tagging>
Where:
KEY_1is the key name for your label. For example,pet.VALUE_1is the value for your label. For example,dog.
Note that you can add multiple
<Tag>elements in a request. If you want to remove all labels on a bucket, use a single, empty<Tag>element in the file:<Tagging> <TagSet> <Tag> </Tag> </TagSet> </Tagging>
Use
cURLto call the XML API with aPUTBucket request andtaggingquery string parameter:curl -X PUT --data-binary @XML_FILE_NAME \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/BUCKET_NAME?tagging"
Where:
XML_FILE_NAMEis the path for the XML file that you created in Step 2.BUCKET_NAMEis the name of the bucket that the label applies to. For example,my-bucket.
View bucket labels
Console
- In the Google Cloud console, go to the Cloud Storage Buckets page.
Click the name of the bucket whose labels you want to view.
Click the Configuration tab.
The labels set on the bucket are listed in the Labels field.
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 describe command with the
--format flag:
gcloud storage buckets describe gs://BUCKET_NAME --format="default(labels)"
Where BUCKET_NAME is the name of the bucket
whose labels you want to view. For example, my-bucket.
If successful and labels exist for the bucket, the response is similar to the following:
labels: red-key: ruby blue-key: cyan
If successful and labels to 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();
std::cout << "The metadata for bucket " << bucket_metadata->name() << " is "
<< *bucket_metadata << "\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;
publicclass GetBucketMetadata{
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";
Storage storage=StorageOptions .newBuilder().setProjectId(projectId).build().getService ();
// Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAME
Bucket bucket=
storage.get (bucketName,Storage.BucketGetOption.fields(Storage.BucketField.values()));
// Print bucket metadata
System.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 library
const{Storage}=require('@google-cloud/storage');
// Creates a client
conststorage=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 Metadata
const[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.cloudimport storage
defbucket_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 .new
bucket=storage.bucketbucket_name
puts"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.each do|key,value|
puts" - #{key} = #{value}"
end
puts"Lifecycle Rules:"
bucket.lifecycle.each do|rule|
puts"#{rule.action } - #{rule.storage_class} - #{rule.age } - #{rule.matches_storage_class }"
end
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 thefields=labelsquery string parameter:curl -X GET \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=labels"
Where
BUCKET_NAMEis the name of the bucket whose labels you want to view. For example,my-bucket.
The response looks like the following example:
{ "labels":{ (your_label_key):your_label_value }, }
XML API
Have gcloud CLI installed and initialized, which lets you generate an access token for the
Authorizationheader.Use
cURLto call the XML API with aGETBucket request andtaggingquery string parameter:curl -X GET \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/BUCKET_NAME?tagging"
Where
BUCKET_NAMEis the name of the bucket whose labels you want to view. For example,my-bucket.
The response looks like the following example:
<Tagging> <TagSet> <Tag> <Key>your_label_key</Key> <Value>your_label_value</Value> </Tag> </TagSet> </Tagging>
What's next
- Learn about bucket tags.
- Get additional bucket metadata.