バケットの作成

このページでは、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 のロールをご覧ください。

プロジェクトにロールを付与する手順については、プロジェクトへのアクセス権を管理するをご覧ください。

新しいバケットを作成する

バケットを初めて作成する場合は、 Google Cloud コンソールでオブジェクト ストレージを検出するまたは Google Cloud CLI ツールを使用してオブジェクト ストレージを検出するをご覧ください。

特定の設定または詳細な構成でバケットを作成するには、次の操作を行います。

コンソール

  1. Google Cloud コンソールで Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. [作成] をクリックします。

  3. [バケットの作成] ページでユーザーのバケット情報を入力します。以下のステップでは、操作を完了した後に [続行] をクリックして、次のステップに進みます。

    1. [始める] セクションで、次の操作を行います。

      • バケット名の要件を満たす、グローバルに一意の名前を入力します。

      • バケットラベルを追加するには、 展開矢印をクリックして [ラベル] セクションを開き、[ラベルを追加] をクリックして、ラベルの keyvalue を指定します。

    2. [データの保存場所の選択] セクションで、次の操作を行います。

      1. ロケーション タイプを選択してください。

      2. ロケーション タイプのプルダウン メニューを使用して、バケット内のオブジェクト データが永続的に保存されるロケーションを選択します。

      3. クロスバケット レプリケーションを設定するには、[Storage Transfer Service 経由でクロスバケット レプリケーションを追加する] を選択し、次の手順を実施します。

        クロスバケット レプリケーションを設定する

        1. [バケット] メニューで、バケットを選択します。
        2. [レプリケーションの設定] セクションで、[構成] をクリックして、レプリケーション ジョブの設定を構成します。

          [クロスバケット レプリケーションを構成する] ペインが表示されます。

          • オブジェクト名の接頭辞で複製するオブジェクトをフィルタするには、オブジェクトを追加または除外する接頭辞を入力し、 [接頭辞を追加] をクリックします。
          • 複製されたオブジェクトのストレージ クラスを設定するには、[ストレージ クラス] メニューからストレージ クラスを選択します。この手順をスキップすると、複製されたオブジェクトはデフォルトで宛先バケットのストレージ クラスを使用します。
          • [完了] をクリックします。

    3. [データの保存場所を選択する] セクションで、次の操作を行います。

      1. バケットのデフォルトのストレージ クラスを選択するか、バケットデータのストレージ クラスを自動的に管理する Autoclass を選択します。

      2. 階層名前空間を有効にするには、[データ量が多いワークロード向けにストレージを最適化] セクションで、[このバケットで階層的な名前空間を有効にする] を選択します。

    4. [オブジェクトへのアクセスを制御する方法を選択する] セクションで、バケットに公開アクセスの防止を適用するかどうかを選択し、バケットのオブジェクトにアクセス制御モデルを選択します。

    5. [オブジェクト データを保護する方法を選択する] セクションで、次の操作を行います。

      • [データ保護] で、バケットに設定するオプションを選択します。

      • 削除(復元可能)を有効にするには、[削除(復元可能)ポリシー] というラベルの付いた 展開矢印をクリックし、削除後にオブジェクトを保持する日数を指定します。

      • オブジェクト データの暗号化方法を選択するには、[データ暗号化] というラベルの付いた 展開矢印をクリックし、データの暗号化方法を選択します。

  4. [作成] をクリックします。

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

コマンドライン

  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

    ここで

    • BUCKET_NAME は、バケットに付ける名前で、命名要件の対象となります。例: my-bucket
    • BUCKET_LOCATION は、バケットのロケーションです。例: US

    リクエストが成功すると、コマンドから次のメッセージが返されます。

    Creating gs://BUCKET_NAME/...

    次のフラグを設定すると、バケットの作成をより細かくコントロールできます。

    • --project: バケットが関連付けられるプロジェクト ID またはプロジェクト番号を指定します。例: my-project
    • --default-storage-class: バケットのデフォルトのストレージ クラスを指定します。例: STANDARD
    • --uniform-bucket-level-access: バケットの均一なバケットレベルのアクセスを有効にします。
    • --soft-delete-duration: 削除(復元可能)の保持期間を指定します。これは、オブジェクトが削除された後に保持する日数を指定します。例: 10d

    例:

    gcloud storage buckets create gs://BUCKET_NAME --project=PROJECT_ID --default-storage-class=STORAGE_CLASS --location=BUCKET_LOCATION --uniform-bucket-level-access
    --soft-delete-duration=RETENTION_DURATION
    

    gcloud CLI を使用してバケットを作成するオプションの完全なリストについては、buckets create オプションをご覧ください。

  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,
       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. gcloud CLI のインストールと初期化を行います。これにより、Authorization ヘッダーのアクセス トークンを生成できます。

    2. バケットの設定を含む JSON ファイルを作成します。この設定には、バケットの name を含める必要があります。設定の一覧については、Buckets:Insert のドキュメントをご覧ください。一般的な設定は次のとおりです。

      {
        "name": "BUCKET_NAME",
        "location": "BUCKET_LOCATION",
        "storageClass": "STORAGE_CLASS",
        "iamConfiguration": {
          "uniformBucketLevelAccess": {
            "enabled": true
          },
        }
      }

      ここで

      • BUCKET_NAME は、バケットに付ける名前で、命名要件の対象となります。例: my-bucket

      • BUCKET_LOCATION は、バケットのオブジェクト データを保存するロケーションです。例: US

      • STORAGE_CLASS は、バケットのデフォルトのストレージ クラスです。例: STANDARD

    3. 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 は、手順 2 で作成した JSON ファイルの名前です。
      • PROJECT_IDENTIFIER は、バケットが関連付けられているプロジェクトの ID または番号です。例: my-project

    XML API

    1. gcloud CLI のインストールと初期化を行います。これにより、Authorization ヘッダーのアクセス トークンを生成できます。

    2. バケットの設定を含む XML ファイルを作成します。設定の全一覧については、XML: バケットを作成するのドキュメントをご覧ください。一般的な設定は次のとおりです。

      <CreateBucketConfiguration>
        <StorageClass>STORAGE_CLASS</StorageClass>
        <LocationConstraint>BUCKET_LOCATION</LocationConstraint>
      </CreateBucketConfiguration>

      ここで

    3. cURL を使用して、XML API を呼び出します。

      curl -X PUT --data-binary @XML_FILE_NAME \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "x-goog-project-id: PROJECT_ID" \
        "https://storage.googleapis.com/BUCKET_NAME"

      ここで

      • XML_FILE_NAME は、手順 2 で作成した XML ファイルの名前です。
      • PROJECT_ID は、バケットが関連付けられるプロジェクトの ID です。例: my-project
      • BUCKET_NAME は、バケットに付ける名前で、命名要件の対象となります。例: my-bucket

      リクエストが成功した場合、レスポンスは返されません。

次のステップ

使ってみる

Google Cloud を初めて使用する場合は、アカウントを作成して、実際のシナリオでの Cloud Storage のパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。

Cloud Storage を無料で試す