Using bucket labels

This page shows you how to add, view, edit, and remove the labels set on a bucket in Cloud Storage. For an overview of buckets and bucket labels, see the Key Terms.

Add a bucket label

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the bucket list, find the bucket you want to apply a label to, and click its Bucket overflow menu ().

  3. Click Edit labels.

  4. In the side panel that appears, click the + Add label button.

  5. Specify a key and value for your label.

  6. Click Save.

In the Edit labels side panel, you can also edit the Value of existing labels.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the -l flag in a label ch command. For example:

gsutil label ch -l [KEY_1]:[VALUE_1] gs://[BUCKET_NAME]/

Where

  • [KEY_1] is the key name for your label. For example, pet.
  • [VALUE_1] is the value for your label. For example, dog.
  • [BUCKET_NAME] is the name of the bucket that the label applies to. For example, my-bucket.

Use multiple -l flags to add or edit multiple key:value pairs in a single command.

Use the label set command to replace all existing labels with new ones.

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& label_key, std::string const& label_value) {
  StatusOr<gcs::BucketMetadata> updated_metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetLabel(label_key, label_value));

  if (!updated_metadata) {
    throw std::runtime_error(updated_metadata.status().message());
  }

  std::cout << "Successfully set label " << label_key << " to " << label_value
            << " on bucket  " << updated_metadata->name() << ".";
  std::cout << " The bucket labels are now:";
  for (auto const& kv : updated_metadata->labels()) {
    std::cout << "\n  " << kv.first << ": " << kv.second;
  }
  std::cout << "\n";
}

Java

For more information, see the Cloud Storage Java API reference documentation.

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.HashMap;
import java.util.Map;

public class AddBucketLabel {
  public static void addBucketLabel(
      String projectId, String bucketName, String labelKey, String labelValue) {
    // 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> labelsToAdd = new HashMap<>();
    labelsToAdd.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) {
      labels = labelsToAdd;
    } else {
      labels.putAll(labelsToAdd);
    }
    bucket.toBuilder().setLabels(labels).build().update();

    System.out.println(
        "Added label " + labelKey + " with value " + labelValue + " to bucket " + bucketName + ".");
  }
}

PHP

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * Adds or updates a bucket label.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $labelName the name of the label to add.
 * @param string $labelValue the value of the label to add.
 */
function add_bucket_label($bucketName, $labelName, $labelValue)
{
    $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);
}

Python

For more information, see the Cloud Storage Python API reference documentation.

import pprint

from google.cloud import storage


def add_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("Updated labels on {}.".format(bucket.name))
    pprint.pprint(bucket.labels)

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "Name of your Google Cloud Storage bucket"
# label_key   = "Cloud Storage bucket Label Key"
# label_value = "Cloud Storage bucket Label Value"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name

bucket.update do |bucket|
  bucket.labels[label_key] = label_value
end

puts "Added label #{label_key} with value #{label_value} to #{bucket_name}"

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. 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.
  3. Use cURL to call the JSON API with a PATCH Bucket request:

    curl -X PATCH --data-binary @[JSON_FILE_NAME].json \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=labels"

    Where:

    • [JSON_FILE_NAME] is the name of the JSON file you created in Step 2.
    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the bucket that the label applies to. For example, my-bucket.

You can add or edit multiple key:value pairs in a request.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .xml file that contains the following information:

    <Tagging>
      <TagSet>
        <Tag>
          <Key>[KEY_1]</Key>
          <Value>[VALUE_1]</Value>
        </Tag>
      </TagSet>
    </Tagging>

    Where:

    • [KEY_1] is the key name for your label. For example, pet.
    • [VALUE_1] is the value for your label. For example, dog.

    Note that you can add multiple <Tag> elements in a request.

  3. Use cURL to call the XML API with a PUT Bucket request and tagging query string parameter:

    curl -X PUT --data-binary @[XML_FILE_NAME].xml \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/[BUCKET_NAME]?tagging"

    Where:

    • [XML_FILE_NAME] is the XML file you created in Step 2.
    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the bucket that the label applies to. For example, my-bucket.

View bucket labels

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. (Optional): You can limit the columns displayed in the Cloud Console bucket list by clicking the Column display options menu (Column options icon.).

  3. In the bucket list, find the bucket you want to verify, and check the entry for Label. You may need to scroll horizontally to view the Label column.

    If your bucket has multiple labels, some may be hidden. When labels are hidden, an expandable button appears. Clicking the button displays all labels for a bucket.

    Bucket list with labels column

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use following gsutil ls command:

gsutil ls -L -b gs://[BUCKET_NAME]/

Where:

  • [BUCKET_NAME] is the bucket whose labels you want to view. For example, my-bucket.

The response looks like the following example:

gs://[BUCKET_NAME]/ :
  Storage class:         STANDARD
  ...
  ...
  Labels:
    {
      "your_label_key": "your_label_value"
    }
  ...

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name, gcs::Fields("labels"));

  if (!bucket_metadata) {
    throw std::runtime_error(bucket_metadata.status().message());
  }

  if (bucket_metadata->labels().empty()) {
    std::cout << "The bucket " << bucket_name << " has no labels set.\n";
    return;
  }

  std::cout << "The labels for bucket " << bucket_name << " are:";
  for (auto const& kv : bucket_metadata->labels()) {
    std::cout << "\n  " << kv.first << ": " << kv.second;
  }
  std::cout << "\n";
}

PHP

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * Prints a list of a bucket's lables.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function get_bucket_labels($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $info = $bucket->info();
    if (isset($info['labels'])) {
        foreach ($info['labels'] as $labelKey => $labelValue) {
            printf('%s: %s' . PHP_EOL, $labelKey, $labelValue);
        }
    }
}

Python

For more information, see the Cloud Storage Python API reference documentation.

import pprint

from google.cloud import storage


def get_bucket_labels(bucket_name):
    """Prints out a bucket's labels."""
    # bucket_name = 'your-bucket-name'
    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)

    labels = bucket.labels
    pprint.pprint(labels)

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name

puts "Labels for #{bucket_name}"
bucket.labels.each do |key, value|
  puts "#{key} = #{value}"
end

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API with a GET Bucket request that includes the fields=labels query string parameter:

    curl -X GET \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=labels"

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is 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

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the XML API with a GET Bucket request and tagging query string parameter:

    curl -X GET \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/[BUCKET_NAME]?tagging"

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is 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>

Remove a bucket label

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the bucket list, find the bucket whose label you want to remove, and click the bucket's Bucket overflow menu ().

  3. Click Edit labels.

  4. Click the X associated with the label you want to remove.

  5. Click Save.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the -d flag in a label ch command. For example:

gsutil label ch -d [KEY_1] gs://[BUCKET_NAME]/

Where:

  • [KEY_1] is the key name for your label. For example, pet.
  • [BUCKET_NAME] is the name of the bucket that the label applies to. For example, my-bucket.

Use the label set command to replace all existing labels with new ones.

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& label_key) {
  StatusOr<gcs::BucketMetadata> updated_metadata = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().ResetLabel(label_key));

  if (!updated_metadata) {
    throw std::runtime_error(updated_metadata.status().message());
  }

  std::cout << "Successfully reset label " << label_key << " on bucket  "
            << updated_metadata->name() << ".";
  if (updated_metadata->labels().empty()) {
    std::cout << " The bucket now has no labels.\n";
    return;
  }
  std::cout << " The bucket labels are now:";
  for (auto const& kv : updated_metadata->labels()) {
    std::cout << "\n  " << kv.first << ": " << kv.second;
  }
  std::cout << "\n";
}

Java

For more information, see the Cloud Storage Java API reference documentation.

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.HashMap;
import java.util.Map;

public class RemoveBucketLabel {
  public static void removeBucketLabel(String projectId, String bucketName, String labelKey) {
    // 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 = new HashMap<>();
    labelsToRemove.put(labelKey, null);

    Bucket bucket = storage.get(bucketName);
    Map<String, String> labels;
    if (bucket.getLabels() == null) {
      labels = new HashMap<>();
    } else {
      labels = new HashMap(bucket.getLabels());
    }
    labels.putAll(labelsToRemove);
    bucket.toBuilder().setLabels(labels).build().update();

    System.out.println("Removed label " + labelKey + " from bucket " + bucketName);
  }
}

PHP

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * Removes a label from a bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $labelName the name of the label to remove.
 */
function remove_bucket_label($bucketName, $labelName)
{
    $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

For more information, see the Cloud Storage Python API reference documentation.

import pprint

from google.cloud import storage


def remove_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("Removed labels on {}.".format(bucket.name))
    pprint.pprint(bucket.labels)

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "Name of your Google Cloud Storage bucket"
# label_key   = "Cloud Storage bucket Label Key"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name

bucket.update do |bucket|
  bucket.labels[label_key] = nil
end

puts "Deleted label #{label_key} from #{bucket_name}"

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the following information:

    {
      "labels": {
        "[KEY_1]": null
      }
    }

    Where:

    • [KEY_1] is the key name for your label. For example, pet.
  3. Use cURL to call the JSON API with a PATCH Bucket request:

    curl -X PATCH --data-binary @[JSON_FILE_NAME].json \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=labels"

    Where:

    • [JSON_FILE_NAME] is the name of the JSON file you created in Step 2.
    • [OAUTH2_TOKEN]is the name of the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the bucket the label applies to. For example, my-bucket.

You can remove multiple key:value pairs in a request.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .xml file that contains the following information:

    <Tagging>
      <TagSet>
        <Tag>
        </Tag>
      </TagSet>
    </Tagging>

    Note that you can add multiple <Tag> elements in a request.

  3. Use cURL to call the XML API with a PUT Bucket request and tagging query string parameter:

    curl -X PUT --data-binary @[XML_FILE_NAME].xml \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/[BUCKET_NAME]?tagging"

    Where:

    • [XML_FILE_NAME] is the name of the XML file you created in Step 2.
    • [OAUTH2_TOKEN]is the name of the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the bucket the label applies to. For example, my-bucket.

What's next