デュアルリージョン ストレージを使用する

概要

このページでは、デュアルリージョン ストレージの使用方法について説明します。

必要なロール

デュアルリージョン バケットを作成するために必要な権限を取得するには、プロジェクトに対するストレージ管理者(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. [バケットの作成] ページでユーザーのバケット情報を入力します。次のステップに進むには、[続行] をクリックします。

    1. [バケットに名前を付ける] で、バケット名の要件を満たす名前を入力します。

    2. [データの保存場所の選択] で、[ロケーション タイプ] の横にある [デュアルリージョン] を選択します。省略可: [ターボ レプリケーションを追加する] チェックボックスをオンにすると、この機能とターボ レプリケーションを組み合わせることができます。

    3. [ロケーション] で、使用する [大陸] と関連する [リージョン] を選択します。

    4. [データのデフォルトのストレージ クラスを選択する] で、バケットのストレージ クラスを選択します。デフォルトのストレージ クラスは、デフォルトでバケットにアップロードされたすべてのオブジェクトに割り当てられます。

    5. [オブジェクトへのアクセスを制御する方法を選択する] で、使用する公開アクセスの防止オプションとアクセス制御オプションを選択します。

    6. [オブジェクト データを保護する方法を選択する] で、オブジェクトのバージョニング保持ポリシー暗号化方法など、使用する保護ツールを選択します。

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

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

コマンドライン

--location フラグと --placement フラグを指定して、buckets create コマンドを使用します。

gcloud storage buckets create gs://BUCKET_NAME --location=MULTI-REGION --placement=REGION_1,REGION_2

ここで

  • BUCKET_NAME は、作成するバケットの名前です。例: my-bucket

  • MULTI-REGION には、基盤となるリージョンに関連付けられたマルチリージョン コードを指定します。たとえば、ASIA-SOUTH1(ムンバイ)と ASIA-SOUTH2(デリー)のリージョンを選択する場合は、IN を使用します。

  • REGION_1 には、バケットのリージョンの地理的位置を指定します。例: ASIA-EAST1

  • REGION_2 には、バケットの 2 つ目のリージョンの地理的位置を指定します。例: ASIA-SOUTHEAST1

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

Creating gs://BUCKET_NAME/...

gcloud storage を使用してバケットを作成するときに使用できるオプションの一覧については、buckets create オプションをご覧ください。

クライアント ライブラリ

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& region_a, std::string const& region_b) {
  auto metadata = client.CreateBucket(
      bucket_name,
      gcs::BucketMetadata().set_custom_placement_config(
          gcs::BucketCustomPlacementConfig{{region_a, region_b}}));
  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 CreateDualRegionBucketSample
{
    public Bucket CreateDualRegionBucket(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name",
        string location = "your-location",
        string region1 = "your-region1-name",
        string region2 = "your-region2-name")
    {
        var client = StorageClient.Create();

        var bucket = new Bucket
        {
            Name = bucketName,
            Location = location,
            CustomPlacementConfig = new Bucket.CustomPlacementConfigData
            {
                DataLocations = new[] { region1, region2 }
            }
        };

        var storageBucket = client.CreateBucket(projectId, bucket);

        Console.WriteLine($"Created storage bucket {storageBucket.Name}" +
            $" in {storageBucket.Location}" +
            $" with location-type {storageBucket.LocationType} and" +
            $" dataLocations {string.Join(",", storageBucket.CustomPlacementConfig.DataLocations)}.");

        return storageBucket;
    }

}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// createBucketDualRegion creates a new dual-region bucket in the project in the
// provided location and regions.
// See https://cloud.google.com/storage/docs/locations#location-dr for more information.
func createBucketDualRegion(w io.Writer, projectID, bucketName string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-name"
	location := "US"
	region1 := "US-EAST1"
	region2 := "US-WEST1"

	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()

	storageDualRegion := &storage.BucketAttrs{
		Location: location,
		CustomPlacementConfig: &storage.CustomPlacementConfig{
			DataLocations: []string{region1, region2},
		},
	}
	bucket := client.Bucket(bucketName)
	if err := bucket.Create(ctx, projectID, storageDualRegion); err != nil {
		return fmt.Errorf("Bucket(%q).Create: %w", bucketName, err)
	}

	attrs, err := bucket.Attrs(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Attrs: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Created bucket %v", bucketName)
	fmt.Fprintf(w, " - location: %v", attrs.Location)
	fmt.Fprintf(w, " - locationType: %v", attrs.LocationType)
	fmt.Fprintf(w, " - customPlacementConfig.dataLocations: %v", attrs.CustomPlacementConfig.DataLocations)
	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.CustomPlacementConfig;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Arrays;

public class CreateBucketDualRegion {

  public static void createBucketDualRegion(
      String projectId,
      String bucketName,
      String location,
      String firstRegion,
      String secondRegion) {
    // The ID of your GCP project.
    // String projectId = "your-project-id";

    // The ID to give your GCS bucket.
    // String bucketName = "your-unique-bucket-name";

    // The location your dual regions will be located in.
    // String location = "US";

    // One of the regions the dual region bucket is to be created in.
    // String firstRegion = "US-EAST1";

    // The second region the dual region bucket is to be created in.
    // String secondRegion = "US-WEST1";

    // See this documentation for other valid locations and regions:
    // https://cloud.google.com/storage/docs/locations

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    CustomPlacementConfig config =
        CustomPlacementConfig.newBuilder()
            .setDataLocations(Arrays.asList(firstRegion, secondRegion))
            .build();

    BucketInfo bucketInfo =
        BucketInfo.newBuilder(bucketName)
            .setLocation(location)
            .setCustomPlacementConfig(config)
            .build();

    Bucket bucket = storage.create(bucketInfo);

    System.out.println(
        "Created bucket "
            + bucket.getName()
            + " in location "
            + bucket.getLocation()
            + " with location type "
            + bucket.getLocationType()
            + " with Custom Placement Config "
            + bucket.getCustomPlacementConfig().toString());
  }
}

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 bucket's pair of regions. Case-insensitive.
// See this documentation for other valid locations:
// https://cloud.google.com/storage/docs/locations
// const location = 'US';
// const region1 = 'US-EAST1';
// const region2 = 'US-WEST1';

// 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 createDualRegionBucket() {
  // For regions supporting dual-regions see: https://cloud.google.com/storage/docs/locations
  const [bucket] = await storage.createBucket(bucketName, {
    location,
    customPlacementConfig: {
      dataLocations: [region1, region2],
    },
  });

  console.log(`Created '${bucket.name}'`);
  console.log(`- location: '${bucket.metadata.location}'`);
  console.log(`- locationType: '${bucket.metadata.locationType}'`);
  console.log(
    `- customPlacementConfig: '${JSON.stringify(
      bucket.metadata.customPlacementConfig
    )}'`
  );
}

createDualRegionBucket().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')
 * @param string $location Location for the bucket's regions. Case-insensitive.
 *        (e.g. 'US')
 * @param string $region1 First region for the bucket's regions. Case-insensitive.
 *        (e.g. 'US-EAST1')
 * @param string $region2 Second region for the bucket's regions. Case-insensitive.
 *        (e.g. 'US-WEST1')
 */
function create_bucket_dual_region(string $bucketName, string $location, string $region1, string $region2): void
{
    $storage = new StorageClient();
    $bucket = $storage->createBucket($bucketName, [
        'location' => $location,
        'customPlacementConfig' => [
            'dataLocations' => [$region1, $region2],
        ],
    ]);

    $info = $bucket->info();

    printf("Created '%s':", $bucket->name());
    printf("- location: '%s'", $info['location']);
    printf("- locationType: '%s'", $info['locationType']);
    printf("- customPlacementConfig: '%s'" . PHP_EOL, print_r($info['customPlacementConfig'], true));
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import storage


def create_bucket_dual_region(bucket_name, location, region_1, region_2):
    """Creates a Dual-Region Bucket with provided location and regions.."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The bucket's pair of regions. Case-insensitive.
    # See this documentation for other valid locations:
    # https://cloud.google.com/storage/docs/locations
    # region_1 = "US-EAST1"
    # region_2 = "US-WEST1"
    # location = "US"

    storage_client = storage.Client()
    bucket = storage_client.create_bucket(bucket_name, location=location, data_locations=[region_1, region_2])

    print(f"Created bucket {bucket_name}")
    print(f" - location: {bucket.location}")
    print(f" - location_type: {bucket.location_type}")
    print(f" - customPlacementConfig data_locations: {bucket.data_locations}")

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

# The ID of your GCS bucket
# bucket_name = "your-bucket-name"

# The bucket's pair of regions. Case-insensitive.
# See this documentation for other valid locations:
# https://cloud.google.com/storage/docs/locations
# region_1 = "US-EAST1"
# region_2 = "US-WEST1"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.create_bucket bucket_name,
                                custom_placement_config: { data_locations: [region_1, region_2] }

puts "Bucket #{bucket.name} created:"
puts "- location: #{bucket.location}"
puts "- location_type: #{bucket.location_type}"
puts "- custom_placement_config:"
puts "  - data_locations: #{bucket.data_locations}"

REST API

JSON API

  1. OAuth 2.0 Playground から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. バケットの設定を含む JSON ファイルを作成します。このファイルに namelocation を含める必要があります。設定の一覧については、Buckets:Insert のドキュメントをご覧ください。一般的な設定は次のとおりです。

    {
      "name": "BUCKET_NAME",
      "location": "MULTI-REGION",
      "customPlacementConfig": {
        "dataLocations": ["REGION_1", "REGION_2"]
        },
      "storageClass": "STORAGE_CLASS"
    }

    ここで

    • BUCKET_NAME は、バケットに付ける名前で、命名要件の対象となります。例: my-bucket
    • MULTI-REGION には、基盤となるリージョンに関連付けられたマルチリージョン コードを指定します。たとえば、ASIA-SOUTH1(ムンバイ)と ASIA-SOUTH2(デリー)のリージョンを選択する場合は、IN を使用します。
    • REGION_1REGION_2 は、バケットのオブジェクト データを保存するリージョンです。たとえば、ASIA-EAST1ASIA-SOUTHEAST1 です。
    • STORAGE_CLASS は、バケットのストレージ クラスです。例: STANDARD
  3. 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_ID"

    ここで

    • JSON_FILE_NAME は手順 2 で作成した JSON ファイルの名前です。
    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • PROJECT_ID は、バケットが関連付けられるプロジェクトの ID です。例: my-project

XML API

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. 次の情報が含まれる XML ファイルを作成します。

      <CreateBucketConfiguration>
         <LocationConstraint>MULTI-REGION</LocationConstraint>
            <CustomPlacementConfig>
               <DataLocations>
                  <DataLocation>REGION_1</DataLocation>
                  <DataLocation>REGION_2</DataLocation>
               </DataLocations>
            </CustomPlacementConfig>
         <StorageClass>STORAGE_CLASS</StorageClass>
      </CreateBucketConfiguration>
     

    ここで

  3. 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

    リクエストにサポートされていないリージョンが含まれている場合は、エラー メッセージが返されます。リクエストが成功した場合、レスポンスは返されません。

次のステップ