Usa archiviazione a due regioni

Overview

In questa pagina viene descritto come utilizzare l'archiviazione a due regioni.

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per la creazione di un bucket a due regioni, chiedi all'amministratore di concederti il ruolo IAM Amministratore Storage (roles/storage.admin) per il progetto.

Questo ruolo predefinito contiene l'autorizzazione necessaria per creare un bucket a due regioni. Per visualizzare le autorizzazioni esatte necessarie, espandi la sezione Autorizzazioni richieste:

Autorizzazioni obbligatorie

  • storage.buckets.create
  • storage.buckets.enableObjectRetention (richiesto solo se si abilitano le configurazioni di conservazione degli oggetti per il bucket)
  • storage.buckets.list (richiesto solo se si crea un bucket utilizzando la console Google Cloud)
  • resourcemanager.projects.get (richiesto solo se si crea un bucket utilizzando la console Google Cloud)

Potresti essere in grado di ottenere queste autorizzazioni anche con i ruoli personalizzati o altri ruoli predefiniti. Per sapere quali ruoli sono associati a quali autorizzazioni, consulta Ruoli IAM per Cloud Storage.

Per istruzioni sulla concessione dei ruoli per i progetti, consulta Gestire l'accesso ai progetti.

Crea un bucket a due regioni

Completa i seguenti passaggi per creare un bucket a due regioni:

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Fai clic su Crea.

  3. Nella pagina Crea un bucket, inserisci le informazioni del bucket. Per andare al passaggio successivo, fai clic su Continua.

    1. In Assegna un nome al bucket, inserisci un nome che soddisfi i requisiti di denominazione dei bucket.

    2. Per Scegli dove archiviare i tuoi dati, accanto a Tipo di località, scegli Due regioni. (Facoltativo) Puoi combinare la funzionalità con la replica turbo, selezionando la casella di controllo Aggiungi replica turbo.

    3. In Località, seleziona il Continente e le Regioni associate che vuoi utilizzare.

    4. In Scegli una classe di archiviazione predefinita per i tuoi dati, seleziona una classe di archiviazione per il bucket. La classe di archiviazione predefinita è assegnata per impostazione predefinita a tutti gli oggetti caricati nel bucket.

    5. Per Scegli come controllare l'accesso agli oggetti, seleziona le opzioni di prevenzione dell'accesso pubblico e di controllo dell'accesso che vuoi utilizzare.

    6. Per Scegli come proteggere i dati degli oggetti, seleziona gli strumenti di protezione che vuoi utilizzare, come il controllo delle versioni degli oggetti, un criterio di conservazione e un metodo di crittografia.

  4. Fai clic su Crea.

    Per scoprire come ottenere informazioni dettagliate sugli errori relativi alle operazioni di Cloud Storage non riuscite nella console Google Cloud, consulta Risoluzione dei problemi.

Riga di comando

Utilizza il comando buckets create con i flag --location e --placement:

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

Dove:

  • BUCKET_NAME è il nome del bucket che stai creando. Ad esempio, my-bucket.

  • MULTI-REGION specifica il codice per più regioni associato alle regioni sottostanti. Ad esempio, quando scegli le regioni ASIA-SOUTH1 (Mumbai) e ASIA-SOUTH2 (Delhi), utilizza IN.

  • REGION_1 specifica la posizione geografica di una regione per il tuo bucket. Ad esempio, ASIA-EAST1.

  • REGION_2 specifica la posizione geografica di una seconda regione per il tuo bucket. Ad esempio, ASIA-SOUTHEAST1.

Se la richiesta ha esito positivo, il comando restituisce il seguente messaggio:

Creating gs://BUCKET_NAME/...

Per un elenco completo delle opzioni disponibili durante la creazione di bucket con gcloud storage, consulta le opzioni per buckets create.

Librerie client

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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#

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

API REST

API JSON

  1. Assicurati che gcloud CLI sia installato e inizializzatoper generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Crea un file JSON contenente le impostazioni per il bucket, che deve includere name e location. Consulta la documentazione Buckets:Insert per un elenco completo delle impostazioni. Di seguito sono riportate alcune impostazioni comuni tra cui:

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

    Dove:

    • BUCKET_NAME è il nome che vuoi assegnare al bucket, soggetto ai requisiti di denominazione. Ad esempio, my-bucket.
    • MULTI-REGION specifica il codice per più regioni associato alle regioni sottostanti. Ad esempio, quando scegli le regioni ASIA-SOUTH1 (Mumbai) e ASIA-SOUTH2 (Delhi), utilizza IN.
    • REGION_1 e REGION_2 sono le regioni in cui vuoi archiviare i dati degli oggetti del bucket. Ad esempio, ASIA-EAST1 e ASIA-SOUTHEAST1.
    • STORAGE_CLASS è la classe di archiviazione del tuo bucket. Ad esempio: STANDARD.
  3. Utilizza cURL per chiamare l'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"

    Dove:

    • JSON_FILE_NAME è il nome del file JSON che hai creato nel passaggio 2.
    • PROJECT_ID è l'ID del progetto a cui verrà associato il bucket. Ad esempio, my-project.

API XML

  1. Assicurati che gcloud CLI sia installato e inizializzatoper generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Crea un file XML contenente le seguenti informazioni:

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

    Dove:

    • MULTI-REGION specifica il codice per più regioni associato alle regioni sottostanti. Ad esempio, quando scegli le regioni ASIA-SOUTH1 (Mumbai) e ASIA-SOUTH2 (Delhi), utilizza IN.
    • REGION_1 e REGION_2 sono le regioni in cui vuoi archiviare i dati degli oggetti del bucket. Ad esempio, ASIA-EAST1 e ASIA-SOUTHEAST1.
    • STORAGE_CLASS è la classe di archiviazione predefinita del tuo bucket. Ad esempio: STANDARD.

  3. Utilizza cURL per chiamare l'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"
    

    Dove:

    • XML_FILE_NAME è il nome del file XML che hai creato nel passaggio 2.
    • PROJECT_ID è l'ID del progetto a cui verrà associato il bucket. Ad esempio, my-project.
    • BUCKET_NAME è il nome che vuoi assegnare al bucket, soggetto ai requisiti di denominazione dei bucket. Ad esempio, my-bucket.

    Se la richiesta include regioni non supportate, viene restituito un messaggio di errore. Se la richiesta ha esito positivo, non viene restituita alcuna risposta.

Passaggi successivi