バケットを作成する

このページでは、Cloud Storage バケットの作成方法について説明します。リクエストで指定されていない限り、バケットは US マルチリージョンで作成され、デフォルトのストレージ クラスは Standard Storage になります。また、削除(復元可能)の保持期間は 7 日間になります。

必要なロール

Cloud Storage バケットを作成するために必要な権限を取得するには、プロジェクトに対するストレージ管理者(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. [作成] をクリックします。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

  1. Google Cloud コンソールで、「Cloud Shell をアクティブにする」をクリックします。

    Cloud Shell をアクティブにする

    Google Cloud コンソールの下部で Cloud Shell セッションが開始し、コマンドライン プロンプトが表示されます。Cloud Shell はシェル環境です。Google Cloud CLI がすでにインストールされており、現在のプロジェクトの値もすでに設定されています。セッションが初期化されるまで数秒かかることがあります。

  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 から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. バケットの設定を含む JSON ファイルを作成します。この設定には、バケットの name を含める必要があります。設定の一覧については、Buckets:Insert のドキュメントをご覧ください。一般的な設定は次のとおりです。
  3. {
      "name": "BUCKET_NAME",
      "location": "BUCKET_LOCATION",
      "storageClass": "STORAGE_CLASS",
      "iamConfiguration": {
        "uniformBucketLevelAccess": {
          "enabled": true
        },
      }
    }

    ここで

  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 から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. バケットの設定を含む XML ファイルを作成します。設定の全一覧については、XML: バケットを作成するのドキュメントをご覧ください。一般的な設定は次のとおりです。
  3. <CreateBucketConfiguration>
       <LocationConstraint>BUCKET_LOCATION</LocationConstraint>
       <StorageClass>STORAGE_CLASS</StorageClass>
    </CreateBucketConfiguration>

    ここで

  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 を無料で試す