建立已啟用階層命名空間的值區

本頁說明如何建立啟用階層式命名空間的值區。

必要的角色

如要取得必要權限,以便建立啟用階層式命名空間的值區,請要求管理員授予您專案的儲存空間管理員 (roles/storage.admin) 身分與存取權管理角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

這個預先定義的角色具備 storage.buckets.create 權限,這是建立啟用階層式命名空間的值區時的必要權限。

您或許還可透過自訂角色或其他預先定義的角色取得這項權限。

建立啟用階層命名空間的值區

控制台

如要在值區上啟用階層式命名空間,請先按照步驟建立新值區,然後執行下列操作:

  1. 在「選擇資料儲存方式」專區中,找到「為資料密集型工作負載提供最理想的儲存空間」專區,然後選取「在這個 bucket 上啟用階層式命名空間」
  2. 完成其餘步驟,即可完成建立值區。

指令列

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

    Activate Cloud Shell

    At the bottom of the Trusted 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 --uniform-bucket-level-access --enable-hierarchical-namespace

    其中:

    • BUCKET_NAME 是您要授予值區的名稱,必須遵守命名要求。例如:my-bucket
    • BUCKET_LOCATION 是值區的位置。例如:us-east1
    • --uniform-bucket-level-access:為值區啟用統一值區層級存取權
    • --enable-hierarchical-namespace:為 bucket 啟用階層命名空間。您無法在現有 bucket 中啟用階層命名空間。

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

    Creating gs://BUCKET_NAME/...

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

    • --project:指定要與值區建立關聯的專案 ID 或專案編號。例如:my-project
    • --default-storage-class:指定值區的預設儲存空間級別。例如:STANDARD
    • 如需使用 Google Cloud CLI 建立水桶的完整選項清單,請參閱 buckets create 選項

    例如:

    gcloud storage buckets create gs://BUCKET_NAME --project=PROJECT_ID --default-storage-class=STORAGE_CLASS --location=BUCKET_LOCATION --uniform-bucket-level-access
  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) {
      auto metadata = client.CreateBucket(
          bucket_name,
          gcs::BucketMetadata()
              .set_hierarchical_namespace(gcs::BucketHierarchicalNamespace{true})
              .set_iam_configuration(gcs::BucketIamConfiguration{
                  gcs::UniformBucketLevelAccess{true, {}}, absl::nullopt}));
      if (!metadata) throw std::move(metadata).status();
    
      std::cout << "Bucket " << metadata->name() << " created."
                << "\nFull Metadata: " << *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 CreateBucketWithHierarchicalNamespaceEnabledSample
    {
        public Bucket CreateBucketWithHierarchicalNamespace(
            string projectId = "your-project-id",
            string bucketName = "your-unique-bucket-name")
        {
            var storage = StorageClient.Create();
            var bucket = storage.CreateBucket(projectId,
                new Bucket
                {
                    Name = bucketName,
                    IamConfiguration = new Bucket.IamConfigurationData
                    {
                        UniformBucketLevelAccess = new Bucket.IamConfigurationData.UniformBucketLevelAccessData { Enabled = true }
                    },
                    HierarchicalNamespace = new Bucket.HierarchicalNamespaceData { Enabled = true }
                });
            Console.WriteLine($"Created {bucketName} with Hierarchical Namespace enabled.");
            return bucket;
        }
    }

    Go

    詳情請參閱 Cloud Storage Go API 參考說明文件

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

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

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"
    
    	"cloud.google.com/go/storage"
    )
    
    // createBucketHierarchicalNamespace creates a new bucket with hierarchical
    // namespace features enabled.
    func createBucketHierarchicalNamespace(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()
    
    	attrs := &storage.BucketAttrs{
    		HierarchicalNamespace: &storage.HierarchicalNamespace{
    			Enabled: true,
    		},
    		// Hierarchical namespace buckets must use uniform bucket-level access.
    		UniformBucketLevelAccess: storage.UniformBucketLevelAccess{
    			Enabled: true,
    		},
    	}
    	bucket := client.Bucket(bucketName)
    	if err := bucket.Create(ctx, projectID, attrs); err != nil {
    		return fmt.Errorf("Bucket(%q).Create: %w", bucketName, err)
    	}
    	fmt.Fprintf(w, "Created bucket %v with hierarchical namespace enabled\n", bucketName)
    	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.BucketInfo.HierarchicalNamespace;
    import com.google.cloud.storage.BucketInfo.IamConfiguration;
    import com.google.cloud.storage.Storage;
    import com.google.cloud.storage.StorageOptions;
    
    public final class CreateHierarchicalNamespaceBucket {
    
      public static void createHierarchicalNamespaceBucket(String projectId, String bucketName)
          throws Exception {
        // The ID of your GCP project
        // String projectId = "your-project-id";
    
        // The ID to give your GCS bucket
        // String bucketName = "your-unique-bucket-name";
        StorageOptions storageOptions = StorageOptions.newBuilder().setProjectId(projectId).build();
        try (Storage storage = storageOptions.getService()) {
    
          BucketInfo bucketInfo =
              BucketInfo.newBuilder(bucketName)
                  .setIamConfiguration(
                      // Hierarchical namespace buckets must use uniform bucket-level access.
                      IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build())
                  .setHierarchicalNamespace(HierarchicalNamespace.newBuilder().setEnabled(true).build())
                  .build();
    
          Bucket bucket = storage.create(bucketInfo);
    
          System.out.printf(
              "Created bucket %s with Hierarchical Namespace enabled.%n", bucket.getName());
        }
      }
    }

    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';
    
    // 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 createBucketWithHierarchicalNamespace() {
      const [bucket] = await storage.createBucket(bucketName, {
        iamConfiguration: {
          uniformBucketLevelAccess: {
            enabled: true,
          },
        },
        hierarchicalNamespace: {
          enabled: true,
        },
      });
    
      console.log(
        `Created '${bucket.name}' with hierarchical namespace enabled.`
      );
    }
    
    createBucketWithHierarchicalNamespace().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 Hierarchical Namespace enabled.
     *
     * @param string $bucketName The name of your Cloud Storage bucket.
     *        (e.g. 'my-bucket')
     */
    function create_bucket_hierarchical_namespace(string $bucketName): void
    {
        $storage = new StorageClient();
        $bucket = $storage->createBucket($bucketName, [
            'hierarchicalNamespace' => ['enabled' => true],
            'iamConfiguration' => ['uniformBucketLevelAccess' => ['enabled' => true]]
        ]);
    
        printf('Created bucket %s with Hierarchical Namespace enabled.', $bucket->name());
    }

    Python

    詳情請參閱 Cloud Storage Python API 參考說明文件

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

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

    from google.cloud import storage
    
    
    def create_bucket_hierarchical_namespace(bucket_name):
        """Creates a bucket with hierarchical namespace enabled."""
        # The ID of your GCS bucket
        # bucket_name = "your-bucket-name"
    
        storage_client = storage.Client()
        bucket = storage_client.bucket(bucket_name)
        bucket.iam_configuration.uniform_bucket_level_access_enabled = True
        bucket.hierarchical_namespace_enabled = True
        bucket.create()
    
        print(f"Created bucket {bucket_name} with hierarchical namespace enabled.")
    
    

    Ruby

    詳情請參閱 Cloud Storage Ruby API 參考說明文件

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

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

    def create_bucket_hierarchical_namespace bucket_name:
      # The ID to give your GCS bucket
      # bucket_name = "your-unique-bucket-name"
    
      require "google/cloud/storage"
    
      storage = Google::Cloud::Storage.new
    
      hierarchical_namespace = Google::Apis::StorageV1::Bucket::HierarchicalNamespace.new enabled: true
    
      storage.create_bucket bucket_name do |b|
        b.uniform_bucket_level_access = true
        b.hierarchical_namespace = hierarchical_namespace
      end
    
      puts "Created bucket #{bucket_name} with Hierarchical Namespace enabled."
    end

    REST API

    JSON API

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

    2. 建立包含值區設定的 JSON 檔案,其中必須包含值區的 name。如需完整的設定清單,請參閱「 Buckets: Insert」說明文件。以下是常見的設定:
    3. {
        "name": "BUCKET_NAME",
        "location": "BUCKET_LOCATION",
        "storageClass": "STORAGE_CLASS",
        "hierarchicalNamespace": {
          "enabled": "BOOLEAN"
        },
        "iamConfiguration": {
          "uniformBucketLevelAccess": {
            "enabled": true
        },
      },
      }

      其中:

      • BUCKET_NAME 是您要授予值區的名稱,必須遵守命名要求。例如:my-bucket
      • BUCKET_LOCATION 是您希望儲存值區物件資料位置。例如:US-EAST1
      • STORAGE_CLASS 是值區的預設儲存空間級別。例如:STANDARD
      • hierarchicalNamespace.enabled 設為 TRUE,即可為 bucket 啟用階層命名空間。您無法在現有 bucket 中啟用階層命名空間。
    4. uniformBucketLevelAccess.enabled 設為 TRUE,為 bucket 啟用統一值區層級存取權。
    5. 使用 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 是包含 bucket 設定的 JSON 檔案名稱。
      • PROJECT_IDENTIFIER 是要與值區建立關聯的專案 ID 或編號。例如:my-project

後續步驟