建立 Bucket

本頁面說明如何建立 Cloud Storage bucket。除非您在要求中另有指定,否則系統會以 Standard storage 預設儲存空間級別建立 bucket,並將虛刪除保留時間設為七天。

如果您是首次建立 bucket,請參閱「使用 Cloud de Confiance 控制台探索物件儲存庫」或「使用 Google Cloud CLI 探索物件儲存庫」,進一步瞭解可透過 Cloud Storage 執行的工作。

必要的角色

如要取得建立 Cloud Storage bucket 的必要權限,請要求管理員授予您專案的 Storage 管理員 (roles/storage.admin) IAM 角色。

這個預先定義的角色具備建立 bucket 所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

  • storage.buckets.create
  • storage.buckets.enableObjectRetention (只有在為 bucket 啟用物件保留設定時才需要)
  • storage.buckets.list (只有在使用 Cloud de Confiance 控制台建立 bucket 時才需要)。
  • resourcemanager.projects.get (只有在使用 Cloud de Confiance 控制台建立 bucket 時才需要)

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。如要查看角色與權限的關聯,請參閱「Cloud Storage 的 IAM 角色」。

如需授予專案角色的操作說明,請參閱「管理專案存取權」。

建立新的 bucket

如要建立具有特定設定或進階設定的 bucket,請完成下列步驟。

控制台

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

    前往「Buckets」(值區) 頁面

  2. 按一下 「建立」。
  3. 在「Create a bucket」(建立 bucket) 頁面中,輸入 bucket 資訊。完成下列每個步驟後,請點選「繼續」前往下一個步驟:

    1. 在「Get started」(開始使用) 部分,執行下列操作:

      • 輸入符合 bucket 名稱規定的全域不重複名稱。

      • 如要新增值區標籤,請按一下 展開箭頭,展開「標籤」部分,然後按一下 「新增標籤」,並為標籤指定 key 和 value。

    2. 在「Choose where to store your data」(選擇資料的儲存位置) 部分,執行下列操作:

      1. 選取「位置類型」。

      2. 使用位置類型下拉式選單,選取要永久儲存 bucket 中物件資料的位置。

        • 如果選取「雙區域」位置類型,也可以勾選相關核取方塊,啟用強化型複製功能。

    3. 在「Choose how to store your data」(選擇資料儲存方式) 部分,執行下列操作:

      1. 為 bucket 選取預設儲存空間級別,或選取「Autoclass」,讓系統自動管理 bucket 資料的儲存空間級別。

      2. 在「Optimize storage for data-intensive workloads」(為資料密集型工作負載提供最理想的儲存空間) 部分,執行下列操作:

        • 如要啟用階層命名空間,請選取「為這個 bucket 啟用階層命名空間」。

        • 如要啟用 Rapid Cache,請選取「Enable Rapid Cache」(啟用 Rapid Cache),然後按照下列步驟操作:
          1. 如要建立快取,請按一下「設定」。

          2. 在隨即顯示的「設定快取設定」對話方塊中,按一下所列區域旁的下拉式箭頭,然後選取要建立快取的區域。

          3. 按一下「完成」。

    4. 在「Choose how to control access to objects」(選取如何控制物件的存取權) 部分,執行下列操作:

      1. 選取 bucket 是否強制執行禁止公開存取。

      2. 為 bucket 的物件選取存取控管模式。建議您選取「Uniform」(統一),在 bucket 上啟用統一 bucket 層級存取權。

      3. 如要設定 bucket 的 IP 過濾功能,請按照下列步驟操作:

        1. 在「IP filtering」(IP 過濾) 部分,按一下 「Configure」(設定)。

        2. 如要允許從公開 IP 位址存取,請按照下列步驟操作:

          1. 按一下「公用網際網路」。
          2. 在「Allowed IP range(s)」(允許的 IP 範圍) 欄位中,指定一或多個要允許的 IPv4 位址範圍或 IPv6 CIDR 範圍。例如 192.0.2.0/24 或 2001:db8::/32。

            為避免無法存取 bucket,請加入自己的 IP 位址。

        3. 如要允許從虛擬私有雲網路存取,請按照下列步驟操作:

          1. 按一下「虛擬私有雲網路」。
          2. 針對每個聯播網執行下列操作:

            1. 按一下「新增虛擬私有雲網路」。
            2. 在「New VPC network」(新增虛擬私有雲網路) 區段中,指定下列資訊:

              • 在「Project ID」欄位中輸入專案 ID。
              • 在「Network name」(網路名稱) 欄位中,輸入網路名稱。
              • 在「允許的 IP 範圍」欄位中,輸入一或多個 IPv4 或 IPv6 CIDR 範圍,例如 192.0.2.0/24 或 2001:db8::/32。

                為避免無法存取 bucket,請加入自己的 IP 位址。

            3. 按一下「完成」。
        4. 如要允許其他組織中受信任的 Cloud de Confiance 服務代理和虛擬私有雲網路略過 IP 過濾設定,請按照下列步驟操作:

          1. 按一下「其他設定」。
          2. 在「Google Cloud 服務代理存取權」部分,選取下列其中一個選項:

            • 允許服務代理存取:啟用這項設定後,BigLake、儲存空間分析、Vertex AI 和 BigQuery 等服務在需要存取這個 bucket 時,可以略過 IP 過濾驗證程序。 Cloud de Confiance
            • 拒絕服務代理存取權:對 Cloud de Confiance 服務代理強制執行 IP 過濾規則。
          3. 在「跨組織虛擬私有雲存取權」部分,執行下列其中一項操作:
            • 如要允許不同 Cloud de Confiance 組織中指定虛擬私有雲網路的存取權,請將切換鈕設為「允許」位置。
            • 如要禁止從貴機構外部的虛擬私有雲網路存取資料,請點選切換鈕,將其設為「拒絕」(預設狀態)。 Cloud de Confiance
        5. 按一下「檢查」,然後按一下「儲存」。
    5. 在「選擇保護物件資料的方式」部分,執行下列操作:

      • 選取「資料保護」下方的任何選項,為 bucket 設定保護措施。

      • 如要變更虛刪除功能在刪除後保留物件的時間長度,請勾選「虛刪除政策」核取方塊,然後選取「設定自訂保留時間長度」選項。然後指定要保留已刪除物件的時間長度。

        如要停用虛刪除功能 (例如 bucket 主要包含短期暫存資料),請取消勾選「Soft delete policy」(虛刪除政策) 核取方塊。

      • 如要選擇如何加密物件資料,請按一下標示為「資料加密」的 展開箭頭,然後執行下列操作:

        • 在「預設加密金鑰類型」部分,選取 bucket 的預設加密金鑰。如果選取「Cloud KMS key」(Cloud KMS 金鑰),請提供 Cloud Key Management Service 金鑰。
        • 在「加密機制強制執行規則」部分的「金鑰類型」,選取要允許或限制 bucket 中新物件使用的加密類型。
  4. 點選「建立」。

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

指令列

  1. 在 Cloud de Confiance 控制台中啟用 Cloud Shell。

    啟用 Cloud Shell

    Cloud de Confiance 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

  2. 在開發環境中執行 gcloud storage buckets create 指令:

    gcloud storage buckets create gs://BUCKET_NAME --location=BUCKET_LOCATION

    其中:

    • BUCKET_NAME 是您要為 bucket 指定的名稱,必須符合命名規定。例如:my-bucket。
    • BUCKET_LOCATION 是 bucket 的位置。例如:U-FRANCE-EAST1。

    如果要求成功,指令會傳回下列訊息:

    Creating gs://BUCKET_NAME/...

    設定下列旗標,進一步控管值區的建立作業:

    • --project:指定要與 bucket 建立關聯的專案 ID 或專案編號。例如:my-project。
    • --default-storage-class:指定 bucket 的預設儲存空間級別。例如:STANDARD。
    • --uniform-bucket-level-access:為 bucket 啟用統一 bucket 層級存取權。
    • --soft-delete-duration:指定虛刪除保留時間長度,也就是物件刪除後要保留的天數。例如:10d。
    • --encryption-enforcement-file:提供檔案,定義 bucket 中新物件受限或允許的加密方法。

    例如:

    gcloud storage buckets create gs://BUCKET_NAME --project=PROJECT_ID --default-storage-class=STORAGE_CLASS --location=BUCKET_LOCATION --uniform-bucket-level-access
    --soft-delete-duration=RETENTION_DURATION --encryption-enforcement-file=ENCRYPTION_ENFORCEMENT_FILE
    

    如需使用 gcloud CLI 建立 bucket 的完整選項清單,請參閱 buckets create 選項。

用戶端程式庫

C++

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

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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& storage_class, std::string const& location) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.CreateBucket(bucket_name, gcs::BucketMetadata()
                                           .set_storage_class(storage_class)
                                           .set_location(location));
  if (!bucket_metadata) throw std::move(bucket_metadata).status();

  std::cout << "Bucket " << bucket_metadata->name() << " created."
            << "\nFull Metadata: " << *bucket_metadata << "\n";
}

C#

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

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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。


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

public class CreateRegionalBucketSample
{
    /// <summary>
    /// Creates a storage bucket with region.
    /// </summary>
    /// <param name="projectId">The ID of the project to create the buckets in.</param>
    /// <param name="location">The location of the bucket. Object data for objects in the bucket resides in 
    /// physical storage within this region. Defaults to US.</param>
    /// <param name="bucketName">The name of the bucket to create.</param>
    /// <param name="storageClass">The bucket's default storage class, used whenever no storageClass is specified
    /// for a newly-created object. This defines how objects in the bucket are stored
    /// and determines the SLA and the cost of storage. Values include MULTI_REGIONAL,
    /// REGIONAL, STANDARD, NEARLINE, COLDLINE, ARCHIVE, and DURABLE_REDUCED_AVAILABILITY.
    /// If this value is not specified when the bucket is created, it will default to
    /// STANDARD.</param>
    public Bucket CreateRegionalBucket(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name",
        string location = "us-west1",
        string storageClass = "REGIONAL")
    {
        var storage = StorageClient.Create();
        Bucket bucket = new Bucket
        {
            Location = location,
            Name = bucketName,
            StorageClass = storageClass
        };
        var newlyCreatedBucket = storage.CreateBucket(projectId, bucket);
        Console.WriteLine($"Created {bucketName}.");
        return newlyCreatedBucket;
    }
}

Go

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

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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

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

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

// createBucketClassLocation creates a new bucket in the project with Storage class and
// location.
func createBucketClassLocation(w io.Writer, projectID, bucketName string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-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*30)
	defer cancel()

	storageClassAndLocation := &storage.BucketAttrs{
		StorageClass: "COLDLINE",
		Location:     "asia",
	}
	bucket := client.Bucket(bucketName)
	if err := bucket.Create(ctx, projectID, storageClassAndLocation); err != nil {
		return fmt.Errorf("Bucket(%q).Create: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Created bucket %v in %v with storage class %v\n", bucketName, storageClassAndLocation.Location, storageClassAndLocation.StorageClass)
	return nil
}

Java

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

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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageClass;
import com.google.cloud.storage.StorageOptions;

public class CreateBucketWithStorageClassAndLocation {
  public static void createBucketWithStorageClassAndLocation(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID to give your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    // See the StorageClass documentation for other valid storage classes:
    // https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/StorageClass.html
    StorageClass storageClass = StorageClass.COLDLINE;

    // See this documentation for other valid locations:
    // http://g.co/cloud/storage/docs/bucket-locations#location-mr
    String location = "ASIA";

    Bucket bucket =
        storage.create(
            BucketInfo.newBuilder(bucketName)
                .setStorageClass(storageClass)
                .setLocation(location)
                .build());

    System.out.println(
        "Created bucket "
            + bucket.getName()
            + " in "
            + bucket.getLocation()
            + " with storage class "
            + bucket.getStorageClass());
  }
}

Node.js

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

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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The name of a storage class
// See the StorageClass documentation for other valid storage classes:
// https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/StorageClass.html
// const storageClass = 'coldline';

// The name of a location
// See this documentation for other valid locations:
// http://g.co/cloud/storage/docs/locations#location-mr
// const location = 'ASIA';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
// The bucket in the sample below will be created in the project associated with this client.
// For more information, please see https://cloud.google.com/docs/authentication/production or https://googleapis.dev/nodejs/storage/latest/Storage.html
const storage = new Storage();

async function createBucketWithStorageClassAndLocation() {
  // For default values see: https://cloud.google.com/storage/docs/locations and
  // https://cloud.google.com/storage/docs/storage-classes
  const [bucket] = await storage.createBucket(bucketName, {
    location,
    [storageClass]: true,
  });

  console.log(
    `${bucket.name} created with ${storageClass} class in ${location}`
  );
}

createBucketWithStorageClassAndLocation().catch(console.error);

PHP

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

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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

use Google\Cloud\Storage\StorageClient;

/**
 * Create a new bucket with a custom default storage class and location.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function create_bucket_class_location(string $bucketName): void
{
    $storage = new StorageClient();
    $storageClass = 'COLDLINE';
    $location = 'ASIA';
    $bucket = $storage->createBucket($bucketName, [
        'storageClass' => $storageClass,
        'location' => $location,
    ]);

    $objects = $bucket->objects([
        'encryption' => [
            'defaultKmsKeyName' => null,
        ]
    ]);

    printf('Created bucket %s in %s with storage class %s', $bucketName, $storageClass, $location);
}

Python

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

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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

from google.cloud import storage


def create_bucket_class_location(bucket_name):
    """
    Create a new bucket in the US region with the coldline storage
    class
    """
    # bucket_name = "your-new-bucket-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    bucket.storage_class = "COLDLINE"
    new_bucket = storage_client.create_bucket(bucket, location="us")

    print(
        "Created bucket {} in {} with storage class {}".format(
            new_bucket.name, new_bucket.location, new_bucket.storage_class
        )
    )
    return new_bucket

Ruby

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

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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

def create_bucket_class_location bucket_name:
  # The ID to give your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.create_bucket bucket_name,
                                  location:      "ASIA",
                                  storage_class: "COLDLINE"

  puts "Created bucket #{bucket.name} in #{bucket.location} with #{bucket.storage_class} class"
end

Rust

use google_cloud_storage::{client::StorageControl, model::Bucket};

pub async fn sample(
    client: &StorageControl,
    project_id: &str,
    bucket_id: &str,
) -> anyhow::Result<()> {
    let bucket = client
        .create_bucket()
        .set_parent("projects/_")
        .set_bucket_id(bucket_id)
        .set_bucket(
            Bucket::new()
                .set_project(format!("projects/{project_id}"))
                .set_storage_class("NEARLINE")
                .set_location("US-CENTRAL1"),
        )
        .send()
        .await?;
    println!("successfully created bucket {bucket:?}");
    Ok(())
}

Terraform

您可以使用 Terraform 資源建立 Storage bucket。

# Create new storage bucket in the US multi-region
# with coldline storage
resource "random_id" "bucket_prefix" {
  byte_length = 8
}

resource "google_storage_bucket" "static" {
  name          = "${random_id.bucket_prefix.hex}-new-bucket"
  location      = "US"
  storage_class = "COLDLINE"

  uniform_bucket_level_access = true
}

REST API

JSON API

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

  2. 建立包含 bucket 設定的 JSON 檔案,其中必須包含 bucket 的 name。如需完整設定清單,請參閱「Buckets:Insert」說明文件。以下是常見的設定:

    {
      "name": "BUCKET_NAME",
      "location": "BUCKET_LOCATION",
      "storageClass": "STORAGE_CLASS",
      "iamConfiguration": {
        "uniformBucketLevelAccess": {
          "enabled": true
        },
      }
    }

    其中:

    • BUCKET_NAME 是您要為 bucket 指定的名稱,須符合命名規定。例如:my-bucket。

    • BUCKET_LOCATION 是要儲存 bucket 物件資料的位置。例如 U-FRANCE-EAST1。

    • STORAGE_CLASS 是 bucket 的預設儲存空間級別。例如:STANDARD。

  3. 使用 cURL 呼叫 JSON API:

    curl -X POST --data-binary @JSON_FILE_NAME \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json" \
     "https://storage.s3nsapis.fr/storage/v1/b?project=PROJECT_IDENTIFIER"

    其中:

    • JSON_FILE_NAME 是您在步驟 2 建立的 JSON 檔案名稱。
    • PROJECT_IDENTIFIER 是 bucket 關聯專案的 ID 或編號。例如:my-project。

XML API

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

  2. 建立包含 bucket 設定的 XML 檔案。如需完整的設定清單,請參閱「XML:建立 bucket」說明文件。以下是常見的設定:

    <CreateBucketConfiguration>
      <StorageClass>STORAGE_CLASS</StorageClass>
      <LocationConstraint>BUCKET_LOCATION</LocationConstraint>
    </CreateBucketConfiguration>

    其中:

    • STORAGE_CLASS 是 bucket 的預設儲存空間級別。例如:STANDARD。

    • BUCKET_LOCATION 是要儲存 bucket 物件資料的位置。例如 U-FRANCE-EAST1。

  3. 使用 cURL 呼叫 XML API:

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "x-goog-project-id: PROJECT_ID" \
      "https://storage.s3nsapis.fr/BUCKET_NAME"

    其中:

    • XML_FILE_NAME 是您在步驟 2 建立的 XML 檔案名稱。
    • PROJECT_ID 是要與 bucket 建立關聯的專案 ID。例如:my-project。
    • BUCKET_NAME 是您要為 bucket 指定的名稱,須符合命名規定。例如:my-bucket。

    如果要求成功,系統不會傳回任何回應。

後續步驟