建立 Bucket

本頁說明如何建立 Cloud Storage 值區。如果未在要求中特別指定,則系統會建立預設儲存空間級別為「Standard Storage」的值區,並將軟刪除保留時間設為七天。

必要的角色

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

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

所需權限

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

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

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

建立新的 bucket

如果是第一次建立值區,請參閱使用 Cloud de Confiance 控制台探索物件儲存空間使用 Google Cloud CLI 工具探索物件儲存空間

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

控制台

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

    前往「Buckets」(值區) 頁面

  2. 按一下「 Create」(建立)
  3. 在「建立 bucket」頁面中,輸入 bucket 資訊。完成下列每個步驟後,請按一下「繼續」前往下一個步驟:
    1. 在「開始使用」部分,執行下列操作:

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

      • 如要新增儲存空間標籤,請按一下 展開箭頭,展開「標籤」部分,然後按一下 「新增標籤」,並為標籤指定 keyvalue

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

      1. 選取「位置類型」

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

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

    3. 在「選擇資料的儲存方式」部分,請執行下列操作:

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

      2. 在「為資料密集型工作負載提供最理想的儲存空間」部分,請執行下列操作:

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

        2. 如要啟用「Anywhere Cache」,請選取「啟用 Anywhere Cache」,然後按照下列步驟操作:
          1. 如要建立快取,請按一下「設定」

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

          3. 按一下 [完成]

    4. 在「Choose how to control access to objects」(選取如何控制物件的存取權) 部分,選取 bucket 是否要強制禁止公開存取,並為 bucket 物件選取存取權控管模型

    5. 在「選擇保護物件資料的方式」部分,請執行下列操作:

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

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

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

  4. 點選「建立」

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

指令列

  1. In the Cloud de Confiance console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Cloud de Confiance 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 是您要授予 bucket 的名稱,必須遵守命名要求。例如:my-bucket
    • BUCKET_LOCATION 是您 bucket 的位置。例如:U-FRANCE-EAST1

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

    Creating gs://BUCKET_NAME/...

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

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

    如要查看建立值區的完整選項清單,請使用 gcloud CLI,並參閱buckets create 選項

  3. 用戶端程式庫

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

    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

    Terraform

    您可以使用 Terraform 資源建立儲存空間 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 是您要授予值區的名稱,必須遵守命名要求。例如:my-bucket

      • BUCKET_LOCATION 是您希望儲存值區物件資料位置。例如:U-FRANCE-EAST1

      • 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.s3nsapis.fr/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:建立 bucket 說明文件。以下是常見的設定:

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

      其中:

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

      • BUCKET_LOCATION 是您希望儲存值區物件資料位置。例如: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 是要與您的值區建立關聯的專案 ID。例如:my-project
      • BUCKET_NAME 是您要授予值區的名稱,必須遵守命名要求。例如:my-bucket

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

後續步驟