Usar armazenamento birregional

Visão geral

Nesta página, você verá como usar o armazenamento de região dupla.

Funções exigidas

Para receber as permissões necessárias para criar um bucket birregional, peça ao administrador para conceder a você o papel do IAM de Administrador do Storage (roles/storage.admin) no projeto.

Este papel predefinido contém a permissão necessária para criar um bucket birregional. Para acessar as permissões exatas necessárias, expanda a seção Permissões necessárias:

Permissões necessárias

  • storage.buckets.create
  • storage.buckets.enableObjectRetention (necessário apenas se ativar as configurações de retenção de objetos para o bucket)
  • storage.buckets.list (obrigatório apenas ao criar um bucket usando o console do Google Cloud)
  • resourcemanager.projects.get (obrigatório apenas ao criar um bucket usando o console do Google Cloud)

Essas permissões também podem ser concedidas com papéis personalizados ou outros papéis predefinidos. Para conferir quais papéis estão associados a quais permissões, consulte Papéis do IAM para o Cloud Storage.

Para instruções sobre como conceder papéis a projetos, consulte Gerenciar o acesso aos projetos.

Criar um bucket birregional

Siga estas etapas para criar um bucket birregional:

Console

  1. No Console do Google Cloud, acesse a página Buckets do Cloud Storage.

    Acessar buckets

  2. Clique em Criar.

  3. Na página Criar um bucket, insira as informações do seu bucket. Para ir à próxima etapa, clique em Continuar.

    1. Em Nomear o bucket, insira um nome que atenda aos requisitos de nomenclatura de bucket.

    2. Em Escolher onde armazenar seus dados, ao lado de Tipo de local, escolha Locais birregionais. Opcional: é possível combinar o recurso com a replicação turbo, marcando a caixa de seleção Adicionar replicação turbo.

    3. Em Local, selecione o Continente e as Regiões associadas que você quer usar.

    4. Em Escolha uma classe de armazenamento padrão para os dados, selecione uma classe de armazenamento para o bucket. A classe de armazenamento padrão é atribuída por padrão a todos os objetos carregados no bucket.

    5. Em Escolha como controlar o acesso a objetos, selecione as opções Prevenção de acesso público e Controle de acesso que você quer usar.

    6. Para Escolher como proteger os dados do objeto selecione as ferramentas de proteção que você quer usar, comocontrole de versões de objetos, uma política de retenção e um método de criptografia.

  4. Clique em Criar.

    Para saber como acessar informações detalhadas de erro sobre operações do Cloud Storage com falha no console do Google Cloud, consulte Solução de problemas.

Linha de comando

Use o comando buckets create com as flags --location e --placement:

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

Em que:

  • BUCKET_NAME é o nome do bucket que você está criando. Por exemplo, my-bucket.

  • MULTI-REGION especifica o código multirregional associado às regiões subjacentes. Por exemplo, ao escolher as regiões ASIA-SOUTH1 (Mumbai) e ASIA-SOUTH2 (Delhi), use IN.

  • REGION_1 especifica a localização geográfica de uma região do bucket. Por exemplo, ASIA-EAST1.

  • REGION_2 especifica a localização geográfica de uma segunda região do bucket. Por exemplo, ASIA-SOUTHEAST1.

Se a solicitação for bem-sucedida, o comando retornará a seguinte mensagem:

Creating gs://BUCKET_NAME/...

Para conferir uma lista completa de opções disponíveis ao criar buckets com gcloud storage, consulte as opções buckets create.

Bibliotecas de cliente

C++

Para mais informações, consulte a documentação de referência da API Cloud Storage C++.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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#

Para mais informações, consulte a documentação de referência da API Cloud Storage C#.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


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

Para mais informações, consulte a documentação de referência da API Cloud Storage Go.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Para mais informações, consulte a documentação de referência da API Cloud Storage Java.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


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

Para mais informações, consulte a documentação de referência da API Cloud Storage Node.js.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

/**
 * 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

Para mais informações, consulte a documentação de referência da API Cloud Storage PHP.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Para mais informações, consulte a documentação de referência da API Cloud Storage Python.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Para mais informações, consulte a documentação de referência da API Cloud Storage Ruby.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

# 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}"

APIs REST

API JSON

  1. Ter a gcloud CLI instalada e inicializadapara gerar um token de acesso para o cabeçalho Authorization.

    Como alternativa, é possível criar um token de acesso usando o OAuth 2.0 Playground e incluí-lo no cabeçalho Authorization.

  2. Crie um arquivo JSON que contenha as configurações do bucket, que precisam incluir name e location. Consulte a documentação Buckets:Insert para ver uma lista completa de configurações. Veja a seguir configurações comuns a serem incluídas:

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

    Em que:

    • BUCKET_NAME é o nome que você quer dar ao bucket, sujeito a requisitos de nomenclatura. Por exemplo, my-bucket.
    • MULTI-REGION especifica o código multirregional associado às regiões subjacentes. Por exemplo, ao escolher as regiões ASIA-SOUTH1 (Mumbai) e ASIA-SOUTH2 (Delhi), use IN.
    • REGION_1 e REGION_2 são as regiões em que você quer armazenar os dados de objetos do bucket. Por exemplo, ASIA-EAST1 e ASIA-SOUTHEAST1.
    • STORAGE_CLASS é a classe de armazenamento padrão do bucket. Por exemplo, STANDARD.
  3. Use cURL para chamar a API JSON:

    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_ID"

    Em que:

    • JSON_FILE_NAME é o nome do arquivo JSON criado na Etapa 2.
    • PROJECT_ID é o ID do projeto ao qual o bucket será associado. Por exemplo, my-project.

API XML

  1. Ter a gcloud CLI instalada e inicializadapara gerar um token de acesso para o cabeçalho Authorization.

    Como alternativa, é possível criar um token de acesso usando o OAuth 2.0 Playground e incluí-lo no cabeçalho Authorization.

  2. Crie um arquivo XML que contenha as seguintes informações:

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

    Em que:

    • MULTI-REGION especifica o código multirregional associado às regiões subjacentes. Por exemplo, ao escolher as regiões ASIA-SOUTH1 (Mumbai) e ASIA-SOUTH2 (Delhi), use IN.
    • REGION_1 e REGION_2 são as regiões em que você quer armazenar os dados de objetos do bucket. Por exemplo, ASIA-EAST1 e ASIA-SOUTHEAST1.
    • STORAGE_CLASS é a classe de armazenamento padrão do bucket. Por exemplo, STANDARD.

  3. Use cURL (em inglês) para chamar a API XML:

      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"
    

    Em que:

    • XML_FILE_NAME é o nome do arquivo XML criado na Etapa 2.
    • PROJECT_ID é o ID do projeto ao qual o bucket será associado. Por exemplo, my-project.
    • BUCKET_NAME é o nome que você quer dar ao bucket, sujeito a requisitos de nomenclatura do bucket. Por exemplo, my-bucket.

    Se a solicitação incluir regiões não compatíveis, uma mensagem de erro será retornada. Se a solicitação foi bem-sucedida, uma resposta não é retornada.

A seguir