建立 Bucket

本頁面說明如何建立 Cloud Storage 值區。如果未在要求中特別指定,則系統會在 US 多地區建立值區,且預設的儲存空間級別為 Standard storage,並設有七天的軟刪除保留期限。

必要的角色

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

這個預先定義的角色包含建立儲存桶所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

  • storage.buckets.create
  • storage.buckets.enableObjectRetention (僅在啟用值區的物件保留設定時才需要)
  • storage.buckets.list (僅在使用 Google Cloud 控制台建立值區時才需要)。
  • resourcemanager.projects.get (只有在使用 Google Cloud 控制台建立值區時才是必填資訊)

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

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

建立新 Bucket

如果您是第一次建立值區,請參閱「使用 Google Cloud 主控台探索物件儲存空間」或「使用 Google Cloud CLI 工具探索物件儲存空間」。

如要建立含有特定設定或進階設定的值區,請完成下列步驟:

控制台

  1. 在 Google Cloud 控制台,前往 Cloud Storage「Buckets」頁面。

    前往「Buckets」(值區) 頁面

  2. 按一下 「Create」(建立)

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

    1. 在「開始使用」部分執行下列操作:

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

      • 如要新增桶標籤,請按一下 展開箭頭,展開「Labels」部分,然後按一下 「Add label」,並為標籤指定 keyvalue

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

      1. 選取「位置類型」

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

        • 如果您選取「雙區域」位置類型,也可以使用相關核取方塊選擇啟用強化型複製功能
      3. 如要設定跨值區複製作業,請選取「新增透過 Storage 移轉服務執行的跨值區複製作業」,然後按照下列步驟操作:

        設定跨 bucket 複製作業

        1. 在「分類」選單中選取分類。
        2. 在「複寫設定」部分,按一下「設定」,為複寫工作設定設定。

          畫面上會顯示「Configure cross-bucket replication」窗格。

          • 如要依物件名稱前置字串篩選要複製的物件,請輸入要納入或排除物件的前置字串,然後按一下 「新增前置字串」
          • 如要為複製的物件設定儲存空間級別,請從「Storage class」選單中選取儲存空間級別。如果略過這個步驟,複製的物件預設會使用目標值區的儲存空間級別。
          • 按一下 [完成]

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

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

      2. 如要啟用階層命名空間,請在「為資料密集型工作負載提供最理想的儲存空間」部分選取「為這個值區啟用階層命名空間」

    4. 在「選取如何控制物件的存取權」專區中,選取值區是否要強制禁止公開存取,並為值區物件選取存取權控管模型

    5. 在「Choose how to protect object data」(選擇保護物件資料的方式) 專區中執行下列操作:

      • 選取「資料保護」下方的任一選項,設定值區。

      • 如要啟用虛刪除功能,請按一下標示為「虛刪除政策」 展開箭頭,然後指定要保留物件的天數。

      • 如要選擇物件資料的加密方式,請按一下標示為「Data encryption」 展開箭頭,然後選取「Data encryption」 方法。

  4. 按一下 [建立]。

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

指令列

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

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

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

    其中:

    • BUCKET_NAME 是您要授予值區的名稱,必須遵守命名規定。例如:my-bucket
    • BUCKET_LOCATION 是資料集的位置。例如:US

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

    Creating gs://BUCKET_NAME/...

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

    • --project:指定要與您的值區建立關聯的專案 ID 或專案號碼。例如:my-project
    • --default-storage-class:指定值區的預設儲存空間級別。例如:STANDARD
    • --uniform-bucket-level-access:為您的值區啟用統一值區層級存取權
    • --soft-delete-policy:指定虛刪除保留期限,也就是物件刪除後要保留的天數。例如:10d

    例如:

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

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

用戶端程式庫

,瞭解建立新值區的其他選項。

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& 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,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。


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,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

/**
 * 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,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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

Terraform

您可以使用 Terraform 資源建立儲存空間桶

# 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 是您要授予值區的名稱,必須遵守命名規定。例如:my-bucket

    • BUCKET_LOCATION 是您希望儲存值區物件資料位置。例如 US

    • STORAGE_CLASS 是值區的預設儲存空間級別。例如: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.googleapis.com/storage/v1/b?project=PROJECT_IDENTIFIER"

    其中:

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

XML API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

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

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

    其中:

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

    • BUCKET_LOCATION 是您希望儲存值區物件資料位置。例如 US

  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.googleapis.com/BUCKET_NAME"

    其中:

    • XML_FILE_NAME 是您在步驟 2 建立的 XML 檔案名稱。
    • PROJECT_ID 是與您的值區建立關聯的專案 ID。例如:my-project
    • BUCKET_NAME 是您要授予值區的名稱,必須遵守命名規定。例如:my-bucket

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

後續步驟

歡迎試用

如果您未曾使用過 Google Cloud,歡迎建立帳戶,親自體驗實際使用 Cloud Storage 的成效。新客戶可以獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。

免費試用 Cloud Storage