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.get
storage.buckets.list
This permission is only required if you plan on using the
Google Cloud console to perform the instructions on this page.
storage.buckets.update
You might also be able to get these permissions with custom roles.
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:
The following sample adds the specified label to a bucket, or modifies the label if it already exists for the bucket:
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;}}
The following sample removes the specified label from a bucket:
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;}}
The following sample adds the specified label to a bucket, or modifies the label if it already exists for the bucket:
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}
The following sample removes the specified label from a bucket:
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}
The following sample adds the specified label to a bucket, or modifies the label if it already exists for the bucket:
importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.util.HashMap;importjava.util.Map;publicclassAddBucketLabel{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);Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Bucketbucket=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+".");}}
The following sample removes the specified label from a bucket:
importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.util.HashMap;importjava.util.Map;publicclassRemoveBucketLabel{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";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Map<String,String>labelsToRemove=newHashMap<>();labelsToRemove.put(labelKey,null);Bucketbucket=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);}}
The following sample adds the specified label to a bucket, or modifies the label if it already exists for the bucket:
/** * 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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();constlabels={[labelKey]:labelValue,};asyncfunctionaddBucketLabel(){awaitstorage.bucket(bucketName).setMetadata({labels});console.log(`Added label to bucket ${bucketName}`);}addBucketLabel().catch(console.error);
The following sample removes the specified label from a bucket:
/** * 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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=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);
The following sample adds the specified label to a bucket, or modifies the label if it already exists for the bucket:
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);}
The following sample removes the specified label from a bucket:
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);}
The following sample adds the specified label to a bucket, or modifies the label if it already exists for the bucket:
importpprintfromgoogle.cloudimportstoragedefadd_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.labelslabels["example"]="label"bucket.labels=labelsbucket.patch()print(f"Updated labels on {bucket.name}.")pprint.pprint(bucket.labels)
The following sample removes the specified label from a bucket:
importpprintfromgoogle.cloudimportstoragedefremove_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.labelsif"example"inlabels:dellabels["example"]bucket.labels=labelsbucket.patch()print(f"Removed labels on {bucket.name}.")pprint.pprint(bucket.labels)
The following sample adds the specified label to a bucket, or modifies the label if it already exists for the bucket:
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.newbucket=storage.bucketbucket_namebucket.updatedo|bucket|bucket.labels[label_key]=label_valueendputs"Added label #{label_key} with value #{label_value} to #{bucket_name}"end
The following sample removes the specified label from a bucket:
defremove_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.newbucket=storage.bucketbucket_namebucket.updatedo|bucket|bucket.labels[label_key]=nilendputs"Deleted label #{label_key} from #{bucket_name}"end
Rust
The following sample adds the specified label to a bucket, or modifies the label if it already exists for the bucket:
usegoogle_cloud_storage::client::StorageControl;usegoogle_cloud_wkt::FieldMask;pubasyncfnsample(client:&StorageControl,bucket_id:&str,label_key:&str,label_value:&str,)->anyhow::Result<()>{letbucket=client.get_bucket().set_name(format!("projects/_/buckets/{bucket_id}")).send().await?;letmetageneration=bucket.metageneration;letmutlabels=bucket.labels.clone();labels.insert(label_key.to_string(),label_value.to_string());letbucket=client.update_bucket().set_bucket(bucket.set_labels(labels)).set_if_metageneration_match(metageneration).set_update_mask(FieldMask::default().set_paths(["labels"])).send().await?;println!("Successfully added label {label_key}={label_value} to bucket {bucket_id}");println!("{:?}",bucket.labels);Ok(())}
The following sample removes the specified label from a bucket:
usegoogle_cloud_storage::client::StorageControl;usegoogle_cloud_wkt::FieldMask;pubasyncfnsample(client:&StorageControl,bucket_id:&str,label_key:&str,)->anyhow::Result<()>{letbucket=client.get_bucket().set_name(format!("projects/_/buckets/{bucket_id}")).send().await?;letmetageneration=bucket.metageneration;letmutlabels=bucket.labels.clone();labels.remove(label_key);letbucket=client.update_bucket().set_bucket(bucket.set_labels(labels)).set_if_metageneration_match(metageneration).set_update_mask(FieldMask::default().set_paths(["labels"])).send().await?;println!("Successfully removed label {label_key} from bucket {bucket_id}");println!("{:?}",bucket.labels);Ok(())}
REST APIs
JSON API
Have gcloud CLI installed and initialized, which lets
you generate an access token for the Authorization header.
Create a JSON file that contains the following information:
{"labels":{"KEY_1":"VALUE_1"}}
Where
KEY_1 is the key name for your label. For
example, pet.
VALUE_1 is the value for your label. For
example, dog. If you want to remove a key, use null in place
of "<var>VALUE_1</var>".
To view a bucket's labels, follow the instructions for displaying a bucket's metadata and look for
the label field in the response.
importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.BucketInfo;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.util.Map;publicclassGetBucketMetadata{publicstaticvoidgetBucketMetadata(StringprojectId,StringbucketName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();// Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAMEBucketbucket=storage.get(bucketName,Storage.BucketGetOption.fields(Storage.BucketField.values()));// Print bucket metadataSystem.out.println("BucketName: "+bucket.getName());System.out.println("DefaultEventBasedHold: "+bucket.getDefaultEventBasedHold());System.out.println("DefaultKmsKeyName: "+bucket.getDefaultKmsKeyName());System.out.println("Id: "+bucket.getGeneratedId());System.out.println("IndexPage: "+bucket.getIndexPage());System.out.println("Location: "+bucket.getLocation());System.out.println("LocationType: "+bucket.getLocationType());System.out.println("Metageneration: "+bucket.getMetageneration());System.out.println("NotFoundPage: "+bucket.getNotFoundPage());System.out.println("RetentionEffectiveTime: "+bucket.getRetentionEffectiveTime());System.out.println("RetentionPeriod: "+bucket.getRetentionPeriod());System.out.println("RetentionPolicyIsLocked: "+bucket.retentionPolicyIsLocked());System.out.println("RequesterPays: "+bucket.requesterPays());System.out.println("SelfLink: "+bucket.getSelfLink());System.out.println("StorageClass: "+bucket.getStorageClass().name());System.out.println("TimeCreated: "+bucket.getCreateTime());System.out.println("VersioningEnabled: "+bucket.versioningEnabled());System.out.println("ObjectRetention: "+bucket.getObjectRetention());if(bucket.getLabels()!=null){System.out.println("\n\n\nLabels:");for(Map.Entry<String,String>label:bucket.getLabels().entrySet()){System.out.println(label.getKey()+"="+label.getValue());}}if(bucket.getLifecycleRules()!=null){System.out.println("\n\n\nLifecycle Rules:");for(BucketInfo.LifecycleRulerule:bucket.getLifecycleRules()){System.out.println(rule);}}}}
To view a bucket's labels, follow the instructions for displaying a bucket's metadata and look for
the label field in the response.
// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiongetBucketMetadata(){/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// Get Bucket Metadataconst[metadata]=awaitstorage.bucket(bucketName).getMetadata();console.log(JSON.stringify(metadata,null,2));}
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-06-09 UTC."],[],[]]