使用值區標籤

本頁說明如何新增、修改、移除及查看 Cloud Storage bucket 設定的標籤

必要的角色

如要取得新增及管理 bucket 標籤所需的權限,請要求管理員授予 bucket 的 Storage 管理員 (roles/storage.admin) IAM 角色。

這個預先定義的角色具備新增及管理值區標籤所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

  • storage.buckets.get
  • storage.buckets.list
    • 如果您打算使用Google Cloud 控制台執行本頁的操作說明,才需要這項權限。
  • storage.buckets.update

您或許還可透過自訂角色取得這些權限。

如需授予值區角色的操作說明,請參閱設定及管理值區的身分與存取權管理政策

新增、修改或移除值區的標籤

控制台

  1. 前往 Google Cloud 控制台的「Cloud Storage bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 在 bucket 清單中,點選要新增、修改或移除標籤的 bucket 名稱。

  3. 在「Bucket details」(值區詳細資料) 頁面中,按一下「Configuration」(設定) 分頁標籤。

  4. 按一下「標籤」的「編輯」圖示 ()

    標籤編輯器視窗隨即開啟。

    1. 如要新增標籤,請按一下「新增標籤」按鈕,並為標籤指定 keyvalue

    2. 如要修改現有標籤,請按一下「值」,然後輸入新值。

    3. 如要移除標籤,請按一下與要移除的標籤相關聯的垃圾桶圖示

  5. 按一下 [儲存]

如要瞭解如何透過 Google Cloud 控制台取得 Cloud Storage 作業失敗的詳細錯誤資訊,請參閱「疑難排解」一文。

指令列

如要新增標籤或更新現有標籤,請將 gcloud storage buckets update 指令搭配 --update-labels 旗標使用。例如:

gcloud storage buckets update gs://BUCKET_NAME --update-labels=KEY_1=VALUE_1

地點

  • BUCKET_NAME 是要套用此標籤的值區名稱。例如:my-bucket
  • KEY_1 是標籤的鍵名稱。例如:pet
  • VALUE_1 是標籤的值。例如:dog

如要移除現有標籤,請使用 -remove-labels 旗標。例如:

gcloud storage buckets update gs://BUCKET_NAME --remove-labels=KEY_1

如要變更多個標籤,請在相關旗標中以逗號分隔的清單加入標籤,然後使用先前的指令。例如:--update-labels=blue-key=cyan,red-key=ruby

如要移除附加至 bucket 的所有標籤,請使用下列指令:

gcloud storage buckets update gs://BUCKET_NAME --clear-labels

用戶端程式庫

C++

詳情請參閱「Cloud Storage C++ API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何將指定標籤新增至值區,或修改值區的現有標籤:

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 = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetLabel(label_key, label_value));
  if (!updated) throw std::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 (auto const& kv : updated->labels()) {
    std::cout << "\n  " << kv.first << ": " << kv.second;
  }
  std::cout << "\n";
}

下例示範如何從值區移除指定標籤:

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 = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().ResetLabel(label_key));
  if (!updated) throw std::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 (auto const& kv : updated->labels()) {
    std::cout << "\n  " << kv.first << ": " << kv.second;
  }
  std::cout << "\n";
}

C#

詳情請參閱「Cloud Storage C# API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何將指定標籤新增至值區,或修改值區的現有標籤:


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class BucketAddLabelSample
{
    public Bucket BucketAddLabel(
        string bucketName = "your-bucket-name",
        string labelKey = "label-key-to-add",
        string labelValue = "label-value-to-add")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        if (bucket.Labels == null)
        {
            bucket.Labels = new Dictionary<string, string>();
        }
        bucket.Labels.Add(labelKey, labelValue);

        bucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Added label {labelKey} with value {labelValue} to bucket {bucketName}.");
        return bucket;
    }
}

下例示範如何從值區移除指定標籤:


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class BucketRemoveLabelSample
{
    public Bucket BucketRemoveLabel(string bucketName = "your-bucket-name", string labelKey = "label-key-to-remove")
    {
        var storage = StorageClient.Create();
        var bucket = 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}.");
        }
        return bucket;
    }
}

Go

詳情請參閱「Cloud Storage Go API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何將指定標籤新增至值區,或修改值區的現有標籤:

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// addBucketLabel adds a label on a bucket.
func addBucketLabel(w io.Writer, bucketName, labelName, labelValue string) error {
	// bucketName := "bucket-name"
	// labelName := "label-name"
	// labelValue := "label-value"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{}
	bucketAttrsToUpdate.SetLabel(labelName, labelValue)
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Added label %q with value %q to bucket %v\n", labelName, labelValue, bucketName)
	return nil
}

下例示範如何從值區移除指定標籤:

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// removeBucketLabel removes a label on a bucket.
func removeBucketLabel(w io.Writer, bucketName, labelName string) error {
	// bucketName := "bucket-name"
	// labelName := "label-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{}
	bucketAttrsToUpdate.DeleteLabel(labelName)
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Removed label %q from bucket %v\n", labelName, bucketName)
	return nil
}

Java

詳情請參閱「Cloud Storage Java API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何將指定標籤新增至值區,或修改值區的現有標籤:


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> newLabels = new HashMap<>();
    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 + ".");
  }
}

下例示範如何從值區移除指定標籤:


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);
  }
}

Node.js

詳情請參閱「Cloud Storage Node.js API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何將指定標籤新增至值區,或修改值區的現有標籤:

/**
 * 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
const storage = new Storage();

const labels = {
  [labelKey]: labelValue,
};

async function addBucketLabel() {
  await storage.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
const storage = new Storage();

async function removeBucketLabel() {
  const labels = {};
  // To remove a label set the value of the key to null.
  labels[labelKey] = null;
  await storage.bucket(bucketName).setMetadata({labels});
  console.log(`Removed labels from bucket ${bucketName}`);
}

removeBucketLabel().catch(console.error);

PHP

詳情請參閱「Cloud Storage PHP API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何將指定標籤新增至值區,或修改值區的現有標籤:

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

詳情請參閱「Cloud Storage Python API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何將指定標籤新增至值區,或修改值區的現有標籤:

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

下例示範如何從值區移除指定標籤:

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

Ruby

詳情請參閱「Cloud Storage Ruby API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何將指定標籤新增至值區,或修改值區的現有標籤:

def add_bucket_label bucket_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.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}"
end

下例示範如何從值區移除指定標籤:

def remove_bucket_label bucket_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.bucket bucket_name

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

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

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 建立包含下列資訊的 JSON 檔案:

    {
      "labels": {
        "KEY_1": "VALUE_1"
      }
    }

    地點

    • KEY_1 是標籤的鍵名稱。例如:pet
    • VALUE_1 是標籤的值。例如:dog。如要移除金鑰,請使用 null 取代 "<var>VALUE_1</var>"
  3. 使用 cURL 透過 PATCH Bucket 要求呼叫 JSON API

    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"

    其中:

    • JSON_FILE_NAME 是您在步驟 2 建立的 JSON 檔案路徑。
    • BUCKET_NAME 是要套用此標籤的值區名稱。例如:my-bucket

您可以在要求中新增、編輯或移除多個 key:value 組合。

XML API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 建立包含下列資訊的 XML 檔案:

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

    其中:

    • KEY_1 是標籤的鍵名稱。例如:pet
    • VALUE_1 是標籤的值。例如:dog

    請注意,您可以在單一要求中新增多個 <Tag> 元素。如要移除值區的所有標籤,請在檔案中使用單一空白的 <Tag> 元素:

    <Tagging>
      <TagSet>
        <Tag>
        </Tag>
      </TagSet>
    </Tagging>
  3. 使用 cURL 透過 PUT 值區要求和 tagging 查詢字串參數呼叫 XML API

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?tagging"

    其中:

    • XML_FILE_NAME 是您在步驟 2 建立的 XML 檔案路徑。
    • BUCKET_NAME 是要套用此標籤的值區名稱。例如:my-bucket

查看值區標籤

控制台

  1. 前往 Google Cloud 控制台的「Cloud Storage bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 按一下要查看標籤的值區名稱。

  3. 點選「設定」分頁標籤。

bucket 上設定的標籤會列在「標籤」欄位中。

如要瞭解如何透過 Google Cloud 控制台取得 Cloud Storage 作業失敗的詳細錯誤資訊,請參閱「疑難排解」一文。

指令列

使用 gcloud storage buckets describe 指令並加上 --format 標記:

gcloud storage buckets describe gs://BUCKET_NAME --format="default(labels)"

其中 BUCKET_NAME 是您要查看其標籤的值區名稱。例如:my-bucket

如果成功,且值區有標籤,回應會類似以下內容:

labels:
  red-key: ruby
  blue-key: cyan

如果成功,且值區沒有標籤,回應會類似下列內容:

null

用戶端程式庫

C++

詳情請參閱「Cloud Storage C++ API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

如要查看 bucket 的標籤,請按照顯示 bucket 中繼資料的操作說明進行,並在回應中尋找標籤欄位。
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);
  if (!bucket_metadata) throw std::move(bucket_metadata).status();

  std::cout << "The metadata for bucket " << bucket_metadata->name() << " is "
            << *bucket_metadata << "\n";
}

C#

詳情請參閱「Cloud Storage C# API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

如要查看 bucket 的標籤,請按照顯示 bucket 中繼資料的操作說明進行,並在回應中尋找標籤欄位。

using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class GetBucketMetadataSample
{
    public Bucket GetBucketMetadata(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { 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 (var label in bucket.Labels)
            {
                Console.WriteLine($"{label.Key}:\t{label.Value}");
            }
        }
        return bucket;
    }
}

Go

詳情請參閱「Cloud Storage Go API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

如要查看 bucket 的標籤,請按照顯示 bucket 中繼資料的操作說明進行,並在回應中尋找標籤欄位。
import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// getBucketMetadata gets the bucket metadata.
func getBucketMetadata(w io.Writer, bucketName string) (*storage.BucketAttrs, error) {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()
	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return nil, 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)
	if attrs.Encryption != nil {
		fmt.Fprintf(w, "DefaultKmsKeyName: %v\n", attrs.Encryption.DefaultKMSKeyName)
	}
	if attrs.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)
	if attrs.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)
	if attrs.Logging != nil {
		fmt.Fprintf(w, "LogBucket: %v\n", attrs.Logging.LogBucket)
		fmt.Fprintf(w, "LogObjectPrefix: %v\n", attrs.Logging.LogObjectPrefix)
	}
	if attrs.CORS != nil {
		fmt.Fprintln(w, "CORS:")
		for _, v := range attrs.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)
		}
	}
	if attrs.Labels != nil {
		fmt.Fprintf(w, "\n\n\nLabels:")
		for key, value := range attrs.Labels {
			fmt.Fprintf(w, "\t%v = %v\n", key, value)
		}
	}
	return attrs, nil
}

Java

詳情請參閱「Cloud Storage Java API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

如要查看 bucket 的標籤,請按照顯示 bucket 中繼資料的操作說明進行,並在回應中尋找標籤欄位。

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

public class GetBucketMetadata {
  public static void getBucketMetadata(String projectId, String bucketName) {
    // 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.LifecycleRule rule : bucket.getLifecycleRules()) {
        System.out.println(rule);
      }
    }
  }
}

Node.js

詳情請參閱「Cloud Storage Node.js API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

如要查看 bucket 的標籤,請按照顯示 bucket 中繼資料的操作說明進行,並在回應中尋找標籤欄位。
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getBucketMetadata() {
  /**
   * 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] = await storage.bucket(bucketName).getMetadata();

  console.log(JSON.stringify(metadata, null, 2));
}

PHP

詳情請參閱「Cloud Storage PHP API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

如要查看 bucket 的標籤,請按照顯示 bucket 中繼資料的操作說明進行,並在回應中尋找標籤欄位。
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

詳情請參閱「Cloud Storage Python API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

如要查看 bucket 的標籤,請按照顯示 bucket 中繼資料的操作說明進行,並在回應中尋找標籤欄位。

from google.cloud import storage


def bucket_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

詳情請參閱「Cloud Storage Ruby API 參考文件」。

如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

如要查看 bucket 的標籤,請按照顯示 bucket 中繼資料的操作說明進行,並在回應中尋找標籤欄位。
def get_bucket_metadata bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_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 API

JSON API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過包含 fields=labels 查詢字串參數的 GET 值區要求呼叫 JSON API

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=labels"

    其中 BUCKET_NAME 是您要查看其標籤的值區名稱。例如:my-bucket

回應類似下列範例:

{
  "labels" : {
     (your_label_key): your_label_value
   },
}

XML API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 GET 值區要求和 tagging 查詢字串參數呼叫 XML API

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?tagging"

    其中 BUCKET_NAME 是您要查看其標籤的值區名稱。例如:my-bucket

回應類似下列範例:

<Tagging>
  <TagSet>
    <Tag>
      <Key>your_label_key</Key>
      <Value>your_label_value</Value>
    </Tag>
  </TagSet>
</Tagging>

後續步驟