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

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

必要的角色

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

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

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

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

控制台

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

    前往「Buckets」(值區) 頁面

  2. 按一下「 Create」(建立)
  3. 在「建立值區」頁面中,輸入值區資訊,然後按一下「繼續」
    1. 在「開始使用」部分執行下列操作:
      1. 輸入符合值區名稱規定的全域不重複值區名稱。
      2. 如要啟用階層命名空間,請按一下展開箭頭,展開「為檔案導向和資料密集型工作負載提供最理想的儲存空間」部分,然後選取「為這個值區啟用階層命名空間」

        注意:您無法在現有值區中啟用階層式命名空間。

      3. 選用:如要新增值區標籤,請按一下 展開箭頭,展開「標籤」部分,然後按一下 「新增標籤」,並為標籤指定 keyvalue
    2. 在「Choose where to store your data」(選擇資料的儲存位置) 專區中執行下列操作:
      1. 選取「區域」做為位置類型
      2. 在「Location」(位置) 清單中,選取要永久儲存值區資料的區域。
    3. 在「Choose a storage class for your data」(為資料選擇儲存空間級別) 專區中,選取值區的「Set a default class」(設定預設級別)

      注意:右側窗格中的「每月預估費用」面板會根據您所選的儲存空間級別和位置,以及預期的資料大小和作業,估算值區的每月費用。

    4. 在「選取如何控制物件的存取權」部分,選取值區是否強制執行禁止公開存取,並為「存取權控管」選擇「統一」

      注意:如果專案的機構政策已強制禁止公開存取,「禁止公開存取」切換按鈕會遭到鎖定。

    5. 在「選擇保護物件資料的方式」部分中,執行下列操作:
      1. 選用:選取「資料保護」方法,例如設定自訂虛刪除政策物件版本管理保留政策
      2. 如要選取「資料加密」方法,請點按標示為「資料加密」 展開箭頭。
  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 --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

用戶端程式庫

C++

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

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

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

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

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

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

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

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

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

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.googleapis.com/storage/v1/b?project=PROJECT_IDENTIFIER"

    其中:

    • JSON_FILE_NAME 是包含 bucket 設定的 JSON 檔案名稱。
    • PROJECT_IDENTIFIER 是要與值區建立關聯的專案 ID 或編號。例如:my-project

後續步驟

歡迎試用

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

免費試用 Cloud Storage