创建存储桶

本页面介绍了如何创建 Cloud Storage 存储桶。除非您在请求中另行指定,否则系统会在 US 多区域中创建存储桶,其默认存储类别为 Standard Storage,并且有七天的软删除保留时长。

所需的角色

为了获得创建 Cloud Storage 存储桶所需的权限,请让您的管理员向您授予项目的 Storage Admin (roles/storage.admin) IAM 角色。

预定义角色可提供创建存储桶所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

  • storage.buckets.create
  • storage.buckets.enableObjectRetention(仅当为存储桶启用对象保留配置时才需要)
  • storage.buckets.list(仅当使用 Google Cloud 控制台创建存储桶时才需要)
  • resourcemanager.projects.get(仅当使用 Google Cloud 控制台创建存储桶时才需要)

您也可以使用自定义角色或其他预定义角色来获取这些权限。要查看哪些角色与哪些权限相关联,请参阅适用于 Cloud Storage 的 IAM 角色

如需了解如何授予项目角色,请参阅管理对项目的访问权限

创建新存储桶

控制台

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

    进入“存储桶”

  2. 点击 + 创建
  3. 创建存储桶页面上,输入您的存储桶信息。如需转到下一步,请点击继续
    • 指定存储桶的名称中,输入符合存储桶名称要求的名称。
    • 选择存储数据的位置部分,选择 位置类型位置,将永久存储存储桶数据。
    • 对于选择数据的存储类别,请为存储桶选择默认的存储类别,或者选择 Autoclass 对存储桶数据进行自动存储类别管理。

      注意:右侧窗格中的每月费用估算面板会根据您选择的存储类别和位置以及您预期的数据大小和操作,估算存储桶的每月费用。

    • 对于选择如何控制对象的访问权限,请选择您的存储桶是否强制执行禁止公开访问,然后选择存储桶对象的访问权限控制模型

      注意:如果项目的组织政策已实施禁止公开访问,则禁止公开访问切换开关处于锁定状态。

    • 对于选择如何保护对象数据,请根据需要配置 保护工具,然后选择 数据加密方法
  4. 点击创建

如需了解如何在 Google Cloud 控制台中获取有关失败的 Cloud Storage 操作的详细错误信息,请参阅问题排查

命令行

  1. 在 Google Cloud 控制台中,激活 Cloud Shell。

    激活 Cloud Shell

    Cloud Shell 会话随即会在 Google Cloud 控制台的底部启动,并显示命令行提示符。Cloud Shell 是一个已安装 Google Cloud CLI 且已为当前项目设置值的 Shell 环境。该会话可能需要几秒钟时间来完成初始化。

  2. 在开发环境中,运行 gcloud storage buckets create 命令:

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

    其中:

    • BUCKET_NAME 是您要为存储桶指定的名称(须遵循命名要求),例如 my-bucket
    • BUCKET_LOCATION 是存储桶的位置,例如 us-east1

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

    Creating gs://BUCKET_NAME/...

    设置以下标志,以便更好地控制存储桶的创建:

    • --project:指定将与您的存储桶相关联的项目 ID 或项目编号,例如 my-project
    • --default-storage-class:指定存储桶的默认存储类别,例如 STANDARD
    • --soft-delete-duration:指定存储桶的软删除保留时长。例如 2w1d
    • --uniform-bucket-level-access:为存储桶启用统一存储桶级访问权限
    • 如需查看 gcloud 存储桶创建的选项的完整列表,请参阅 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,
   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. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。如需了解相关说明,请参阅 API 身份验证
  2. 创建一个包含存储桶设置的 JSON 文件,其中必须包含存储桶的 name。如需查看完整的设置列表,请参阅存储桶:插入文档。以下是一些常用的设置,包括:
  3. {
      "name": "BUCKET_NAME",
      "location": "BUCKET_LOCATION",
      "storageClass": "STORAGE_CLASS",
      "iamConfiguration": {
        "uniformBucketLevelAccess": {
          "enabled": true
        },
      }
    }

    其中:

    • BUCKET_NAME 是您要为自己的存储桶指定的名称(须遵循命名要求),例如 my-bucket
    • BUCKET_LOCATION 是您要用于存储自己的存储桶对象数据位置,例如 US-EAST1
    • STORAGE_CLASS 是您存储桶的默认存储类别,例如 STANDARD
  4. 使用 cURL 调用 JSON API
    curl -X POST --data-binary @JSON_FILE_NAME \
         -H "Authorization: Bearer OAUTH2_TOKEN" \
         -H "Content-Type: application/json" \
         "https://storage.googleapis.com/storage/v1/b?project=PROJECT_IDENTIFIER"

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的 JSON 文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • PROJECT_IDENTIFIER 是将与您的存储桶相关联的项目的 ID 或编号,例如 my-project

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。如需了解相关说明,请参阅 API 身份验证
  2. 创建包含存储桶设置的 XML 文件。如需查看完整的设置列表,请参阅 XML:创建存储桶文档。以下是一些常用的设置,包括:
  3. <CreateBucketConfiguration>
       <LocationConstraint>BUCKET_LOCATION</LocationConstraint>
       <StorageClass>STORAGE_CLASS</StorageClass>
    </CreateBucketConfiguration>

    其中:

    • BUCKET_LOCATION 是您要用于存储自己的存储桶对象数据位置,例如 US-EAST1
    • STORAGE_CLASS 是您存储桶的默认存储类别,例如 STANDARD
  4. 使用 cURL 调用 XML API
    curl -X PUT --data-binary @XML_FILE_NAME \
         -H "Authorization: Bearer OAUTH2_TOKEN" \
         -H "x-goog-project-id: PROJECT_ID" \
         "https://storage.googleapis.com/BUCKET_NAME"

    其中:

    • XML_FILE_NAME 是您在第 2 步中创建的 XML 文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • PROJECT_ID 是将与您的存储桶相关联的项目的 ID,例如 my-project
    • BUCKET_NAME 是您要为自己的存储桶指定的名称(须遵循命名要求),例如 my-bucket

后续步骤

自行试用

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

免费试用 Cloud Storage