创建启用了分层命名空间的存储桶

本页面介绍了如何创建已启用分层命名空间的存储桶。

所需的角色

如需获得创建启用分层命名空间的存储桶所需的权限,请让您的管理员为您授予项目的 Storage Admin (roles/storage.admin) IAM 角色。 如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

此预定义角色包含创建已启用分层命名空间的存储桶所需的 storage.buckets.create 权限。

您也可以使用自定义角色或其他预定义角色来获取此权限。

创建启用了分层命名空间的存储桶

控制台

  1. 在 Google Cloud 控制台中,转到 Cloud Storage 存储桶页面。

    进入“存储桶”

  2. 点击 创建
  3. 创建存储桶页面上,输入您的存储桶信息。完成以下每一步后,点击继续以继续执行后续步骤:
    1. 开始使用部分中,执行以下操作:

    2. 选择数据存储位置部分中,执行以下操作:

      1. 选择位置类型

      2. 使用位置类型的下拉菜单选择一个位置,用于永久存储存储桶中的对象数据。

    3. 选择数据存储方式部分,执行以下操作:

      1. 为存储桶选择默认存储类别,或者选择 Autoclass 对存储桶数据进行自动存储类别管理。

      2. 针对数据密集型工作负载优化存储部分中,执行以下操作:

        1. 如需启用分层命名空间,请选择在此存储桶上启用分层命名空间

        2. 选择如何控制对对象的访问权限部分中,选择存储桶是否强制执行禁止公开访问,然后为存储桶对象选择访问权限控制模型

        3. 选择如何保护对象数据部分中,执行以下操作:

          • 数据保护下,选择您要为存储桶设置的任何选项。

          • 如需启用软删除,请点击标有软删除政策 展开箭头,然后指定您希望在删除对象后保留对象的天数。

          • 如需选择对象数据的加密方式,请点击标有数据加密 展开箭头,然后选择数据加密方法

      3. 点击创建

      如需了解如何在 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:为存储桶启用分层命名空间。您无法在现有存储桶中启用分层命名空间。

    如果请求成功,该命令将返回以下消息:

    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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

    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。如需查看完整的设置列表,请参阅存储桶:插入文档。以下是一些常用的设置,包括:
    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,以便为存储桶启用分层命名空间。您无法在现有存储桶中启用分层命名空间。
    4. uniformBucketLevelAccess.enabled 设置为 TRUE,以便为存储桶启用统一存储桶级访问权限。
    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 是包含存储桶设置的 JSON 文件的名称。
      • PROJECT_IDENTIFIER 是与存储桶相关联的项目 ID 或编号。例如 my-project

后续步骤

自行试用

如果您是 Google Cloud 新手,请创建一个账号来评估 Cloud Storage 在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。

免费试用 Cloud Storage