Criar e gerenciar configurações de instâncias

Esta página descreve como listar, criar, atualizar, excluir e mostrar os detalhes de uma configuração de instância do Spanner. Algumas funcionalidades de configuração de instâncias personalizadas não estão disponíveis na interface do console do Google Cloud. Nesses casos, use os comandos da Google Cloud CLI (gcloud). fornecidas.

Listar configurações de instância

É possível listar todas as configurações de instância do Spanner disponíveis com a CLI do Google Cloud e as bibliotecas de cliente. Para encontrar uma lista de todas as configurações de instância do Spanner, consulte Configurações regionais e multirregionais.

gcloud

Execute o comando gcloud spanner instance-configs list:

gcloud spanner instance-configs list

C++

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

void ListInstanceConfigs(
    google::cloud::spanner_admin::InstanceAdminClient client,
    std::string const& project_id) {
  int count = 0;
  auto project = google::cloud::Project(project_id);
  for (auto& config : client.ListInstanceConfigs(project.FullName())) {
    if (!config) throw std::move(config).status();
    ++count;
    std::cout << "Instance config [" << count << "]:\n"
              << config->DebugString();
  }
  if (count == 0) {
    std::cout << "No instance configs found in project " << project_id << "\n";
  }
}

C#

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Spanner.Admin.Instance.V1;
using System;
using System.Collections.Generic;
using System.Linq;

public class ListInstanceConfigsSample
{
    public IEnumerable<InstanceConfig> ListInstanceConfigs(string projectId)
    {
        var instanceAdminClient = InstanceAdminClient.Create();
        var projectName = ProjectName.FromProject(projectId);
        var instanceConfigs = instanceAdminClient.ListInstanceConfigs(projectName);

        // We print the first 5 elements for demonstration purposes.
        // You can print all configs in the sequence by removing the call to Take(5).
        // The sequence will lazily fetch elements in pages as needed.
        foreach (var instanceConfig in instanceConfigs.Take(5))
        {
            Console.WriteLine($"Available leader options for instance config {instanceConfig.InstanceConfigName.InstanceConfigId}:");
            foreach (var leader in instanceConfig.LeaderOptions)
            {
                Console.WriteLine(leader);
            }

            Console.WriteLine($"Available optional replica for instance config {instanceConfig.InstanceConfigName.InstanceConfigId}:");
            foreach (var optionalReplica in instanceConfig.OptionalReplicas)
            {
                Console.WriteLine($"Replica type - {optionalReplica.Type}, default leader location - {optionalReplica.DefaultLeaderLocation}, location - {optionalReplica.Location}");
            }
        }
        return instanceConfigs;
    }
}

Go

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
	"google.golang.org/api/iterator"
)

// istInstanceConfigs gets available leader options for all instances
func listInstanceConfigs(w io.Writer, projectName string) error {
	// projectName = `projects/<project>
	ctx := context.Background()
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer instanceAdmin.Close()

	request := &instancepb.ListInstanceConfigsRequest{
		Parent: projectName,
	}
	for {
		iter := instanceAdmin.ListInstanceConfigs(ctx, request)
		for {
			ic, err := iter.Next()
			if err == iterator.Done {
				break
			}
			if err != nil {
				return err
			}
			fmt.Fprintf(w, "Available leader options for instance config %s: %v\n", ic.Name, ic.LeaderOptions)
		}
		pageToken := iter.PageInfo().Token
		if pageToken == "" {
			break
		} else {
			request.PageToken = pageToken
		}
	}

	return nil
}

Java

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.InstanceConfig;
import com.google.spanner.admin.instance.v1.ProjectName;

public class ListInstanceConfigsSample {

  static void listInstanceConfigs() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    listInstanceConfigs(projectId);
  }

  static void listInstanceConfigs(String projectId) {
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .build()
            .getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {
      final ProjectName projectName = ProjectName.of(projectId);
      for (InstanceConfig instanceConfig :
          instanceAdminClient.listInstanceConfigs(projectName).iterateAll()) {
        System.out.printf(
            "Available leader options for instance config %s: %s%n",
            instanceConfig.getName(),
            instanceConfig.getLeaderOptionsList()
        );
      }
    }
  }
}

Node.js

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const projectId = 'my-project-id';

// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = spanner.getInstanceAdminClient();

async function listInstanceConfigs() {
  // Lists all available instance configurations in the project.
  // See https://cloud.google.com/spanner/docs/instance-configurations#configuration for a list of all available
  // configurations.
  const [instanceConfigs] = await instanceAdminClient.listInstanceConfigs({
    parent: instanceAdminClient.projectPath(projectId),
  });
  console.log(`Available instance configs for project ${projectId}:`);
  instanceConfigs.forEach(instanceConfig => {
    console.log(
      `Available leader options for instance config ${
        instanceConfig.name
      } ('${instanceConfig.displayName}'): 
         ${instanceConfig.leaderOptions.join()}`
    );
  });
}
listInstanceConfigs();

PHP

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;
use Google\Cloud\Spanner\Admin\Instance\V1\ListInstanceConfigsRequest;

/**
 * Lists the available instance configurations.
 * Example:
 * ```
 * list_instance_configs();
 * ```
 *
 * @param string $projectId The Google Cloud project ID.
 */
function list_instance_configs(string $projectId = null): void
{
    $instanceAdminClient = new InstanceAdminClient();
    $projectName = InstanceAdminClient::projectName($projectId);
    $request = new ListInstanceConfigsRequest();
    $request->setParent($projectName);
    $resp = $instanceAdminClient->listInstanceConfigs($request);
    foreach ($resp as $element) {
        printf(
            'Available leader options for instance config %s: %s' . PHP_EOL,
            $element->getDisplayName(),
            implode(',', iterator_to_array($element->getLeaderOptions()))
        );
    }
}

Python

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

def list_instance_config():
    """Lists the available instance configurations."""
    from google.cloud.spanner_admin_instance_v1.types import \
        spanner_instance_admin

    spanner_client = spanner.Client()

    request = spanner_instance_admin.ListInstanceConfigsRequest(
        parent=spanner_client.project_name
    )
    for config in spanner_client.instance_admin_api.list_instance_configs(
        request=request
    ):
        print(
            "Available leader options for instance config {}: {}".format(
                config.name, config.leader_options
            )
        )

Ruby

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

# project_id  = "Your Google Cloud project ID"

require "google/cloud/spanner"
require "google/cloud/spanner/admin/instance"

instance_admin_client = Google::Cloud::Spanner::Admin::Instance.instance_admin

project_path = instance_admin_client.project_path project: project_id
configs = instance_admin_client.list_instance_configs parent: project_path

configs.each do |c|
  puts "Available leader options for instance config #{c.name} : #{c.leader_options}"
end

Mostrar detalhes de configuração da instância

É possível mostrar os detalhes de qualquer configuração de instância com o Google Cloud CLI e bibliotecas de cliente. Quando você criar uma nova configuração de instância personalizada; é possível adicionar qualquer local listado em optionalReplicas como uma réplica opcional. Se o local desejado da réplica somente leitura não for exibido, você poderá solicitar uma nova região de réplica somente leitura opcional.

Para mais informações, consulte Crie uma configuração de instância personalizada.

gcloud

Execute o comando gcloud spanner instance-configs describe:

gcloud spanner instance-configs describe INSTANCE-CONFIG

Forneça o seguinte valor:

INSTANCE-CONFIG
A configuração da instância, que define a localização geográfica do e afeta a replicação dos dados. Por exemplo, eur6 ou us-central1.

Para mostrar os detalhes da configuração base eur6, execute:

gcloud spanner instance-configs describe eur6

Confira um exemplo de saída para a configuração de base eur6:

  configType: GOOGLE_MANAGED
  displayName: Europe (Netherlands, Frankfurt)
  freeInstanceAvailability: UNSUPPORTED
  leaderOptions:
  - europe-west3
  - europe-west4
  name: projects/cloud-spanner-demo/instanceConfigs/eur6
  optionalReplicas:
  - displayName: South Carolina
    labels:
      cloud.googleapis.com/country: US
      cloud.googleapis.com/location: us-east1
      cloud.googleapis.com/region: us-east1
    location: us-east1
    type: READ_ONLY
  - displayName: South Carolina
    labels:
      cloud.googleapis.com/country: US
      cloud.googleapis.com/location: us-east1
      cloud.googleapis.com/region: us-east1
    location: us-east1
    type: READ_ONLY
  replicas:
  - defaultLeaderLocation: true
    location: europe-west4
    type: READ_WRITE
  - location: europe-west4
    type: READ_WRITE
  - location: europe-west3
    type: READ_WRITE
  - location: europe-west3
    type: READ_WRITE
  - location: europe-west6
    type: WITNESS

Outras observações sobre o uso:

  • baseConfig (somente para configurações personalizadas) aponta para a configuração de instância de base. Consulte as configurações regionais disponíveis. e as configurações multirregionais disponíveis para listas de configurações de instância base que podem ser usadas para criar uma configuração personalizada da instância.
  • configType indica se essa configuração de instância é uma configuração de instância básica ou personalizada.
  • etag (somente para configurações personalizadas) é uma representação de string codificada em base64 da configuração. É usada para simultaneidade otimista controle

C++

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

void GetInstanceConfig(google::cloud::spanner_admin::InstanceAdminClient client,
                       std::string const& project_id,
                       std::string const& config_id) {
  auto project = google::cloud::Project(project_id);
  auto config = client.GetInstanceConfig(project.FullName() +
                                         "/instanceConfigs/" + config_id);
  if (!config) throw std::move(config).status();
  std::cout << "The instanceConfig " << config->name()
            << " exists and its metadata is:\n"
            << config->DebugString();
}

C#

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


using Google.Cloud.Spanner.Admin.Instance.V1;
using System;
using System.Threading.Tasks;

public class GetInstanceConfigAsyncSample
{
    public async Task<InstanceConfig> GetInstanceConfigAsync(string projectId, string instanceConfigId)
    {
        var instanceAdminClient = await InstanceAdminClient.CreateAsync();
        var instanceConfigName = InstanceConfigName.FromProjectInstanceConfig(projectId, instanceConfigId);
        var instanceConfig = await instanceAdminClient.GetInstanceConfigAsync(instanceConfigName);

        Console.WriteLine($"Available leader options for instance config {instanceConfigName.InstanceConfigId}:");
        foreach (var leader in instanceConfig.LeaderOptions)
        {
            Console.WriteLine(leader);
        }
        return instanceConfig;
    }
}

Go

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
)

// getInstanceConfig gets available leader options
func getInstanceConfig(w io.Writer, instanceConfigName string) error {
	// defaultLeader = `nam3`
	ctx := context.Background()
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer instanceAdmin.Close()

	ic, err := instanceAdmin.GetInstanceConfig(ctx, &instancepb.GetInstanceConfigRequest{
		Name: instanceConfigName,
	})

	if err != nil {
		return fmt.Errorf("could not get instance config %s: %w", instanceConfigName, err)
	}

	fmt.Fprintf(w, "Available leader options for instance config %s: %v", instanceConfigName, ic.LeaderOptions)

	return nil
}

Java

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.InstanceConfig;
import com.google.spanner.admin.instance.v1.InstanceConfigName;

public class GetInstanceConfigSample {

  static void getInstanceConfig() {
    // TODO(developer): Replace these variables before running the sample.
    final String projectId = "my-project";
    final String instanceConfigId = "nam6";
    getInstanceConfig(projectId, instanceConfigId);
  }

  static void getInstanceConfig(String projectId, String instanceConfigId) {
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .build()
            .getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {
      final InstanceConfigName instanceConfigName = InstanceConfigName.of(projectId,
          instanceConfigId);

      final InstanceConfig instanceConfig =
          instanceAdminClient.getInstanceConfig(instanceConfigName.toString());

      System.out.printf(
          "Available leader options for instance config %s: %s%n",
          instanceConfig.getName(),
          instanceConfig.getLeaderOptionsList()
      );
    }
  }
}

Node.js

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const projectId = 'my-project-id';

// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = spanner.getInstanceAdminClient();

async function getInstanceConfig() {
  // Get the instance config for the multi-region North America 6 (NAM6).
  // See https://cloud.google.com/spanner/docs/instance-configurations#configuration for a list of all available
  // configurations.
  const [instanceConfig] = await instanceAdminClient.getInstanceConfig({
    name: instanceAdminClient.instanceConfigPath(projectId, 'nam6'),
  });
  console.log(
    `Available leader options for instance config ${instanceConfig.name} ('${
      instanceConfig.displayName
    }'): 
         ${instanceConfig.leaderOptions.join()}`
  );
}
getInstanceConfig();

PHP

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;
use Google\Cloud\Spanner\Admin\Instance\V1\GetInstanceConfigRequest;

/**
 * Gets the leader options for the instance configuration.
 *
 * @param string $projectId The Google Cloud Project ID.
 * @param string $instanceConfig The name of the instance configuration.
 */
function get_instance_config(string $projectId, string $instanceConfig): void
{
    $instanceAdminClient = new InstanceAdminClient();
    $instanceConfigName = InstanceAdminClient::instanceConfigName($projectId, $instanceConfig);

    $request = (new GetInstanceConfigRequest())
        ->setName($instanceConfigName);
    $configInfo = $instanceAdminClient->getInstanceConfig($request);

    printf('Available leader options for instance config %s: %s' . PHP_EOL,
        $instanceConfig,
        implode(',', array_keys(iterator_to_array($configInfo->getLeaderOptions())))
    );
}

Python

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

def get_instance_config(instance_config):
    """Gets the leader options for the instance configuration."""
    spanner_client = spanner.Client()
    config_name = "{}/instanceConfigs/{}".format(
        spanner_client.project_name, instance_config
    )
    config = spanner_client.instance_admin_api.get_instance_config(name=config_name)
    print(
        "Available leader options for instance config {}: {}".format(
            instance_config, config.leader_options
        )
    )

Ruby

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

# project_id  = "Your Google Cloud project ID"
# instance_config_id = "Spanner instance config ID"

require "google/cloud/spanner"
require "google/cloud/spanner/admin/instance"

instance_admin_client = Google::Cloud::Spanner::Admin::Instance.instance_admin

instance_config_path = instance_admin_client.instance_config_path \
  project: project_id, instance_config: instance_config_id
config = instance_admin_client.get_instance_config name: instance_config_path

puts "Available leader options for instance config #{config.name} : #{config.leader_options}"

Criar uma configuração de instância personalizada

É possível criar uma configuração de instância regional ou multirregional personalizada e adicionar réplicas somente leitura opcionais para dimensionar leituras e oferecer suporte a leituras desatualizadas de baixa latência. Consulte as listas de configurações regionais disponíveis e configurações multirregionais disponíveis para ver as configurações de instâncias básicas que podem ser usadas para criar uma configuração de instância personalizada. Não é possível criar um configuração de instâncias birregionais. Para mais informações sobre a replicação e os tipos de réplica do Spanner, consulte Replicação.

Para criar uma configuração de instância personalizada, você precisa ter a permissão spanner.instanceConfigs.create. Por padrão, os papéis que têm a permissão spanner.instances.create também têm a spanner.instanceConfigs.create.

Console

Não é possível criar uma configuração de instância personalizada usando o console do Google Cloud. Para criar uma instância com réplicas somente leitura, use a CLI gcloud; ou bibliotecas de cliente.

gcloud

Use o comando gcloud spanner instance-configs create:

gcloud spanner instance-configs create CUSTOM-INSTANCE-CONFIG-ID  \
 --display-name=DISPLAY-NAME \
 --base-config=BASE-CONFIG \
 --labels=KEY=VALUE,[...] \
 --replicas=location=LOCATION, type=TYPE[:...]

É possível usar a sinalização --clone-config como uma maneira conveniente de clonar outro configuração de instância básica ou personalizada, além de declarar o local e o tipo de uma réplica personalizada específica.

  gcloud spanner instance-configs create CUSTOM-INSTANCE-CONFIG-ID  \
  --display-name=DISPLAY-NAME \
  --clone-config=INSTANCE-CONFIG \
  --labels=KEY=VALUE,[...] \
  --add-replicas=location=LOCATION, type=TYPE[:...] \
  --skip-replicas=location=LOCATION, type=TYPE[:...]

Forneça os valores a seguir:

CUSTOM-INSTANCE-CONFIG-ID
Um identificador permanente exclusivo no projeto do Google Cloud. Não será possível mudar o ID da configuração da instância depois. O custom- prefixo é obrigatório para evitar conflitos de nome com a instância de base personalizadas.
DISPLAY-NAME
O nome a ser mostrado para a configuração de instância personalizada no console do Google Cloud.
Se você optar por usar as flags `--base-config` e `--replicas`, forneça os seguintes valores:
BASE-CONFIG
O nome da região da configuração da instância base em que a configuração da instância personalizada é baseada. Por exemplo, eur6 ou regional-us-central1.
LOCATION
O nome da região dos recursos de veiculação (réplicas), por exemplo, us-east1. Para descobrir quais nomes de locais são aceitos, execute gcloud spanner instance-configs describe INSTANCE-CONFIG e consulte os replicas e optionalReplicas listas.
TYPE
O tipo de réplica. Para saber quais locais e são aceitos, execute gcloud spanner instance-configs describe INSTANCE-CONFIG e consulte replicas e optionalReplicas. Os tipos são um dos seguintes:
  • READ_ONLY
  • READ_WRITE
  • WITNESS
Os itens na lista são separados por ":".
A menos que a flag --[clone-config] seja usada, todas as réplicas LOCATION e TYPE precisam ser especificadas ao criar uma configuração de instância personalizada, incluindo as predefinidas na configuração de base. Para mais informações, consulte o gcloud instance-configs describe help-text.

Se você optar por usar as sinalizações --clone-config e --add-replicas (somente use --skip-replicas se houver réplicas que você quer deixar de serem clonado), forneça os seguintes valores:

  • --clone-config=INSTANCE-CONFIG

    Use essa flag como uma maneira conveniente de clonar outra configuração de instância base ou personalizada, declarando o local e o tipo de uma réplica personalizada específica. Em seguida, use --add-replicas=location=LOCATION,type=TYPE para especificar onde você quer adicionar a réplica opcional.

    Por exemplo, para criar uma configuração de instância personalizada com duas Réplicas somente leitura em us-east1 enquanto copia todas as outras réplicas da configuração da instância base eur6, execute:

    gcloud spanner instance-configs create custom-eur6 --clone-config=eur6 \
    --add-replicas=location=us-east1,type=READ_ONLY:location=us-east1,type=READ_ONLY
    
  • --skip-replicas=location=LOCATION,type=TYPE

    Use essa flag para pular a clonagem de qualquer réplica.

    Por exemplo, para criar uma configuração de instância personalizada com uma réplica somente leitura em us-east4, copiando todos os outros locais de réplica da configuração de instância de base nam3, exceto a réplica somente leitura em us-central1, execute:

    gcloud spanner instance-configs create custom-nam3 --clone-config=nam3 \
      --add-replicas=location=us-east4,type=READ_ONLY \
      --skip-replicas=location=us-central1,type=READ_ONLY
    

As sinalizações e os valores a seguir são opcionais:

  • --labels=KEY=VALUE,[...]

    KEY e VALUE: uma lista de pares de chave-valor para adicionar à configuração da instância personalizada.

    As chaves precisam começar com um caractere minúsculo e conter apenas hifens (-), sublinhados (_), caracteres minúsculos e números. Os valores precisam conter apenas hifens (-), sublinhados (_), caracteres minúsculos e números.

  • --validate-only

    Use essa flag para validar se a solicitação vai ser bem-sucedida antes de executá-la.

Por exemplo, para criar uma configuração de instância personalizada com a base eur6 com uma réplica somente leitura extra em us-east1, execute:

gcloud spanner instance-configs create custom-eur6 \
  --display-name="Custom eur6" --clone-config=eur6 \
  --add-replicas=location=us-east1,type=READ_ONLY \

Você também pode criar uma configuração de instância personalizada sem o Sinalização --clone-config:

gcloud spanner instance-configs create custom-eur6 \
  --display-name="Custom eur6" --base-config=eur6 \
  --replicas=location=europe-west4,type=READ_WRITE:location=europe-west3,type=READ_WRITE:location=europe-west4,type=READ_WRITE:location=europe-west3,type=READ_WRITE:location=europe-west6,type=WITNESS:location=us-east1,type=READ_ONLY

Você verá esta resposta:

Creating instance-config...done.

C++

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

void CreateInstanceConfig(
    google::cloud::spanner_admin::InstanceAdminClient client,
    std::string const& project_id, std::string const& user_config_id,
    std::string const& base_config_id) {
  auto project = google::cloud::Project(project_id);
  auto base_config = client.GetInstanceConfig(
      project.FullName() + "/instanceConfigs/" + base_config_id);
  if (!base_config) throw std::move(base_config).status();
  if (base_config->optional_replicas().empty()) {
    throw std::runtime_error("No optional replicas in base config");
  }
  google::spanner::admin::instance::v1::CreateInstanceConfigRequest request;
  request.set_parent(project.FullName());
  request.set_instance_config_id(user_config_id);
  auto* request_config = request.mutable_instance_config();
  request_config->set_name(project.FullName() + "/instanceConfigs/" +
                           user_config_id);
  request_config->set_display_name("My instance config");
  // The user-managed instance config must contain all the replicas
  // of the base config plus at least one of the optional replicas.
  *request_config->mutable_replicas() = base_config->replicas();
  for (auto const& replica : base_config->optional_replicas()) {
    *request_config->add_replicas() = replica;
  }
  request_config->set_base_config(base_config->name());
  *request_config->mutable_leader_options() = base_config->leader_options();
  request.set_validate_only(false);
  auto user_config = client.CreateInstanceConfig(request).get();
  if (!user_config) throw std::move(user_config).status();
  std::cout << "Created instance config [" << user_config_id << "]:\n"
            << user_config->DebugString();
}

C#

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


using System;
using System.Threading.Tasks;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Spanner.Admin.Instance.V1;

public class CreateInstanceConfigAsyncSample
{
    public async Task<InstanceConfig> CreateInstanceConfigAsync(string projectId, string baseInstanceConfigId, string customInstanceConfigId)
    {
        InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();
        var instanceConfigName = new InstanceConfigName(projectId, baseInstanceConfigId);
        var instanceConfig = await instanceAdminClient.GetInstanceConfigAsync(instanceConfigName);

        var customInstanceConfigName = new InstanceConfigName(projectId, customInstanceConfigId);

        //Create a custom config.
        InstanceConfig userInstanceConfig = new InstanceConfig
        {
            DisplayName = "C# test custom instance config",
            ConfigType = InstanceConfig.Types.Type.UserManaged,
            BaseConfigAsInstanceConfigName = instanceConfigName,
            InstanceConfigName = customInstanceConfigName,
            //The replicas for the custom instance configuration must include all the replicas of the base
            //configuration, in addition to at least one from the list of optional replicas of the base
            //configuration.
            Replicas = { instanceConfig.Replicas },
            OptionalReplicas =
            {
                new ReplicaInfo
                {
                    Type = ReplicaInfo.Types.ReplicaType.ReadOnly,
                    Location = "us-east1",
                    DefaultLeaderLocation = false
                },
                //The replicas for the custom instance configuration must include all the replicas of the base
                //configuration, in addition to at least one from the list of optional replicas of the base
                //configuration.
                instanceConfig.OptionalReplicas
            }
        };

        var operationResult = await instanceAdminClient.CreateInstanceConfigAsync(new CreateInstanceConfigRequest
        {
            ParentAsProjectName = ProjectName.FromProject(projectId),
            InstanceConfig = userInstanceConfig,
            InstanceConfigId = customInstanceConfigId
        });

        var pollResult = await operationResult.PollUntilCompletedAsync();

        if (pollResult.IsFaulted)
        {
            throw pollResult.Exception;
        }

        Console.WriteLine($"Instance config created successfully");
        Console.WriteLine($"Available custom replication options for instance config {pollResult.Result.Name}\r\n{pollResult.Result.OptionalReplicas}");

        return pollResult.Result;
    }
}

Go

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


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

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
)

// createInstanceConfig creates a custom spanner instance config
func createInstanceConfig(w io.Writer, projectID, userConfigID, baseConfigID string) error {
	// projectID := "my-project-id"
	// userConfigID := "custom-config", custom config names must start with the prefix “custom-”.
	// baseConfigID := "my-base-config"

	// Add timeout to context.
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()

	adminClient, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer adminClient.Close()
	baseConfig, err := adminClient.GetInstanceConfig(ctx, &instancepb.GetInstanceConfigRequest{
		Name: fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, baseConfigID),
	})
	if err != nil {
		return fmt.Errorf("createInstanceConfig.GetInstanceConfig: %w", err)
	}
	if baseConfig.OptionalReplicas == nil || len(baseConfig.OptionalReplicas) == 0 {
		return fmt.Errorf("CreateInstanceConfig expects base config with at least from the list of optional replicas")
	}
	op, err := adminClient.CreateInstanceConfig(ctx, &instancepb.CreateInstanceConfigRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		// Custom config names must start with the prefix “custom-”.
		InstanceConfigId: userConfigID,
		InstanceConfig: &instancepb.InstanceConfig{
			Name:        fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, userConfigID),
			DisplayName: "custom-golang-samples",
			ConfigType:  instancepb.InstanceConfig_USER_MANAGED,
			// The replicas for the custom instance configuration must include all the replicas of the base
			// configuration, in addition to at least one from the list of optional replicas of the base
			// configuration.
			Replicas:   append(baseConfig.Replicas, baseConfig.OptionalReplicas...),
			BaseConfig: baseConfig.Name,
			Labels:     map[string]string{"go_cloud_spanner_samples": "true"},
		},
	})
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Waiting for create operation on projects/%s/instanceConfigs/%s to complete...\n", projectID, userConfigID)
	// Wait for the instance configuration creation to finish.
	i, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Waiting for instance config creation to finish failed: %w", err)
	}
	// The instance configuration may not be ready to serve yet.
	if i.State != instancepb.InstanceConfig_READY {
		fmt.Fprintf(w, "InstanceConfig state is not READY yet. Got state %v\n", i.State)
	}
	fmt.Fprintf(w, "Created instance configuration [%s]\n", userConfigID)
	return nil
}

Java

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.CreateInstanceConfigRequest;
import com.google.spanner.admin.instance.v1.InstanceConfig;
import com.google.spanner.admin.instance.v1.InstanceConfigName;
import com.google.spanner.admin.instance.v1.ProjectName;
import com.google.spanner.admin.instance.v1.ReplicaInfo;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class CreateInstanceConfigSample {

  static void createInstanceConfig() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String baseInstanceConfigId = "nam11";
    String instanceConfigId = "custom-instance-config4";

    createInstanceConfig(projectId, baseInstanceConfigId, instanceConfigId);
  }

  static void createInstanceConfig(
      String projectId, String baseInstanceConfigId, String instanceConfigId) {
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .build()
            .getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {
      final InstanceConfigName baseInstanceConfigName = InstanceConfigName.of(projectId,
          baseInstanceConfigId);
      final InstanceConfig baseConfig =
          instanceAdminClient.getInstanceConfig(baseInstanceConfigName.toString());
      final InstanceConfigName instanceConfigName = InstanceConfigName.of(projectId,
          instanceConfigId);
      /**
       * The replicas for the custom instance configuration must include all the replicas of the
       * base configuration, in addition to at least one from the list of optional replicas of the
       * base configuration.
       */
      final List<ReplicaInfo> replicas =
          Stream.concat(baseConfig.getReplicasList().stream(),
              baseConfig.getOptionalReplicasList().stream().limit(1)).collect(Collectors.toList());
      final InstanceConfig instanceConfig =
          InstanceConfig.newBuilder().setName(instanceConfigName.toString())
              .setBaseConfig(baseInstanceConfigName.toString())
              .setDisplayName("Instance Configuration").addAllReplicas(replicas).build();
      final CreateInstanceConfigRequest createInstanceConfigRequest =
          CreateInstanceConfigRequest.newBuilder().setParent(ProjectName.of(projectId).toString())
              .setInstanceConfigId(instanceConfigId).setInstanceConfig(instanceConfig).build();
      try {
        System.out.printf("Waiting for create operation for %s to complete...\n",
            instanceConfigName);
        InstanceConfig instanceConfigResult =
            instanceAdminClient.createInstanceConfigAsync(
                createInstanceConfigRequest).get(5, TimeUnit.MINUTES);
        System.out.printf("Created instance configuration %s\n", instanceConfigResult.getName());
      } catch (ExecutionException | TimeoutException e) {
        System.out.printf(
            "Error: Creating instance configuration %s failed with error message %s\n",
            instanceConfig.getName(), e.getMessage());
      } catch (InterruptedException e) {
        System.out.println(
            "Error: Waiting for createInstanceConfig operation to finish was interrupted");
      }
    }
  }
}

Node.js

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const instanceConfigId = 'custom-my-instance-config-id'
// const baseInstanceConfigId = 'my-base-instance-config-id';
// const projectId = 'my-project-id';

// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = spanner.getInstanceAdminClient();

// Creates a new instance config
async function createInstanceConfig() {
  const [baseInstanceConfig] = await instanceAdminClient.getInstanceConfig({
    name: instanceAdminClient.instanceConfigPath(
      projectId,
      baseInstanceConfigId
    ),
  });
  try {
    console.log(
      `Creating instance config ${instanceAdminClient.instanceConfigPath(
        projectId,
        instanceConfigId
      )}.`
    );
    const [operation] = await instanceAdminClient.createInstanceConfig({
      instanceConfigId: instanceConfigId,
      parent: instanceAdminClient.projectPath(projectId),
      instanceConfig: {
        name: instanceAdminClient.instanceConfigPath(
          projectId,
          instanceConfigId
        ),
        baseConfig: instanceAdminClient.instanceConfigPath(
          projectId,
          baseInstanceConfigId
        ),
        displayName: instanceConfigId,
        replicas: baseInstanceConfig.replicas.concat(
          baseInstanceConfig.optionalReplicas[0]
        ),
      },
    });
    console.log(
      `Waiting for create operation for ${instanceConfigId} to complete...`
    );
    await operation.promise();
    console.log(`Created instance config ${instanceConfigId}.`);
  } catch (err) {
    console.error(
      'ERROR: Creating instance config ',
      instanceConfigId,
      ' failed with error message ',
      err
    );
  }
}
createInstanceConfig();

PHP

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

use Google\Cloud\Spanner\Admin\Instance\V1\CreateInstanceConfigRequest;
use Google\Cloud\Spanner\Admin\Instance\V1\GetInstanceConfigRequest;
use Google\Cloud\Spanner\Admin\Instance\V1\InstanceConfig;
use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;
use Google\Cloud\Spanner\Admin\Instance\V1\ReplicaInfo;

/**
 * Creates a customer managed instance configuration.
 * Example:
 * ```
 * create_instance_config($instanceConfigId);
 * ```
 *
 * @param string $projectId The Google Cloud Project ID.
 * @param string $instanceConfigId The customer managed instance configuration id. The id must start with 'custom-'.
 * @param string $baseConfigId Base configuration ID to be used for creation, e.g. nam11.
 */
function create_instance_config(string $projectId, string $instanceConfigId, string $baseConfigId): void
{
    $instanceAdminClient = new InstanceAdminClient();
    $projectName = InstanceAdminClient::projectName($projectId);
    $instanceConfigName = $instanceAdminClient->instanceConfigName(
        $projectId,
        $instanceConfigId
    );

    // Get a Google Managed instance configuration to use as the base for our custom instance configuration.
    $baseInstanceConfig = $instanceAdminClient->instanceConfigName(
        $projectId,
        $baseConfigId
    );

    $request = new GetInstanceConfigRequest(['name' => $baseInstanceConfig]);
    $baseInstanceConfigInfo = $instanceAdminClient->getInstanceConfig($request);

    $instanceConfig = (new InstanceConfig())
        ->setBaseConfig($baseInstanceConfig)
        ->setName($instanceConfigName)
        ->setDisplayName('My custom instance configuration')
        ->setLabels(['php-cloud-spanner-samples' => true])
        ->setReplicas(array_merge(
            iterator_to_array($baseInstanceConfigInfo->getReplicas()),
            [new ReplicaInfo([
            'location' => 'us-east1',
            'type' => ReplicaInfo\ReplicaType::READ_ONLY,
            'default_leader_location' => false
            ])]
        ));

    $request = new CreateInstanceConfigRequest([
        'parent' => $projectName,
        'instance_config' => $instanceConfig,
        'instance_config_id' => $instanceConfigId
    ]);
    $operation = $instanceAdminClient->createInstanceConfig($request);

    print('Waiting for operation to complete...' . PHP_EOL);
    $operation->pollUntilComplete();

    printf('Created instance configuration %s' . PHP_EOL, $instanceConfigId);
}

Python

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

def create_instance_config(user_config_name, base_config_id):
    """Creates the new user-managed instance configuration using base instance config."""

    # user_config_name = `custom-nam11`
    # base_config_id = `projects/<project>/instanceConfigs/nam11`
    spanner_client = spanner.Client()
    base_config = spanner_client.instance_admin_api.get_instance_config(
        name=base_config_id
    )

    # The replicas for the custom instance configuration must include all the replicas of the base
    # configuration, in addition to at least one from the list of optional replicas of the base
    # configuration.
    replicas = []
    for replica in base_config.replicas:
        replicas.append(replica)
    replicas.append(base_config.optional_replicas[0])
    operation = spanner_client.instance_admin_api.create_instance_config(
        parent=spanner_client.project_name,
        instance_config_id=user_config_name,
        instance_config=spanner_instance_admin.InstanceConfig(
            name="{}/instanceConfigs/{}".format(
                spanner_client.project_name, user_config_name
            ),
            display_name="custom-python-samples",
            config_type=spanner_instance_admin.InstanceConfig.Type.USER_MANAGED,
            replicas=replicas,
            base_config=base_config.name,
            labels={"python_cloud_spanner_samples": "true"},
        ),
    )
    print("Waiting for operation to complete...")
    operation.result(OPERATION_TIMEOUT_SECONDS)

    print("Created instance configuration {}".format(user_config_name))

Ruby

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

require "google/cloud/spanner"
require "google/cloud/spanner/admin/instance"

def spanner_create_instance_config project_id:, user_config_name:, base_config_id:
  # project_id  = "Your Google Cloud project ID"
  # user_config_name = "Your custom instance configuration name, The name must start with 'custom-'"
  # base_config_id = "Base configuration ID to be used for creation, e.g projects/<project>/instanceConfigs/nam11"

  instance_admin_client = Google::Cloud::Spanner::Admin::Instance.instance_admin
  project_path = instance_admin_client.project_path project: project_id
  base_instance_config = instance_admin_client.get_instance_config name: base_config_id
  # The replicas for the custom instance configuration must include all the replicas of the base
  # configuration, in addition to at least one from the list of optional replicas of the base
  # configuration.
  custom_replicas = []
  base_instance_config.replicas.each do |replica|
    custom_replicas << replica
  end
  custom_replicas << base_instance_config.optional_replicas[0]
  custom_instance_config_id = instance_admin_client.instance_config_path \
    project: project_id, instance_config: user_config_name
  custom_instance_config = {
    name: custom_instance_config_id,
    display_name: "custom-ruby-samples",
    config_type: :USER_MANAGED,
    replicas: custom_replicas,
    base_config: base_config_id,
    labels: { ruby_cloud_spanner_samples: "true" }
  }
  request = {
    parent: project_path,
    # Custom config names must start with the prefix “custom-”.
    instance_config_id: user_config_name,
    instance_config: custom_instance_config
  }
  job = instance_admin_client.create_instance_config request

  puts "Waiting for create instance config operation to complete"

  job.wait_until_done!

  if job.error?
    puts job.error
  else
    puts "Created instance configuration #{user_config_name}"
  end
end

Criar uma instância em uma configuração de instância personalizada

É possível criar uma instância em uma configuração de instância personalizada.

Console

Para criar uma instância em uma configuração de instância personalizada, use o CLI gcloud ou bibliotecas de cliente.

gcloud

Depois de criar a configuração da instância personalizada, siga as instruções fornecidas em Criar uma instância.

C++

Depois de criar a configuração de instância personalizada, siga as instruções em Criar uma instância.

C#

Depois de criar a configuração de instância personalizada, siga as instruções em Criar uma instância.

Go

Depois de criar a configuração da instância personalizada, siga as instruções fornecidas em Criar uma instância.

Java

Depois de criar a configuração de instância personalizada, siga as instruções em Criar uma instância.

Node.js

Depois de criar a configuração de instância personalizada, siga as instruções em Criar uma instância.

PHP

Depois de criar a configuração de instância personalizada, siga as instruções em Criar uma instância.

Python

Depois de criar a configuração da instância personalizada, siga as instruções fornecidas em Criar uma instância.

Ruby

Depois de criar a configuração de instância personalizada, siga as instruções em Criar uma instância.

Atualizar uma configuração de instância personalizada

É possível alterar o nome de exibição e os rótulos de uma configuração de instância personalizada.

Não é possível mudar ou atualizar as réplicas da configuração da instância personalizada. No entanto, é possível criar uma nova configuração de instância personalizada com réplicas e, em seguida, mover a instância para a nova configuração personalizada da instância com as réplicas adicionais escolhidas. Por exemplo: Se a instância estiver em us-central1 e você quiser adicionar uma réplica somente leitura us-west1, você precisa criar uma configuração de instância personalizada com us-central1 como a configuração básica e adicione us-west1 como um arquivo réplica. Em seguida, mova sua instância para esta uma nova configuração de instância personalizada.

gcloud

Use o comando gcloud spanner instance-configs update:

gcloud spanner instance-configs update CUSTOM-INSTANCE-CONFIG-ID \
  --display-name=NEW-DISPLAY-NAME \
  --update-labels=KEY=VALUE,[...], \
  --etag=ETAG

Forneça os valores a seguir:

CUSTOM-INSTANCE-CONFIG-ID
Um identificador permanente da configuração de instância personalizada. Ele vai começar com custom-.
NEW-DISPLAY-NAME
O novo nome a ser exibido para a configuração da instância no console do Google Cloud.
KEY e VALUE
Uma lista de pares de chave-valor a serem atualizados.
As chaves precisam começar com uma letra minúscula e conter apenas hifens (-), sublinhados (_), caracteres minúsculos e números. Os valores precisam conter apenas hifens (-), sublinhados (_), caracteres minúsculos e números.

As sinalizações e os valores a seguir são opcionais:

  • --etag=ETAG: o argumento ETAG pode ser usado para selecionar e ignorar atualizações simultâneas em um cenário de leitura-modificação-gravação.
  • --validate-only: use essa sinalização para validar se a solicitação será bem-sucedida. antes da execução.

Exemplo:

gcloud spanner instance-configs update custom-eur6 \
  --display-name="Customer managed europe replicas"

C++

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

void UpdateInstanceConfig(
    google::cloud::spanner_admin::InstanceAdminClient client,
    std::string const& project_id, std::string const& config_id) {
  auto project = google::cloud::Project(project_id);
  auto config = client.GetInstanceConfig(project.FullName() +
                                         "/instanceConfigs/" + config_id);
  if (!config) throw std::move(config).status();
  google::spanner::admin::instance::v1::UpdateInstanceConfigRequest request;
  auto* request_config = request.mutable_instance_config();
  request_config->set_name(config->name());
  request_config->mutable_labels()->insert({"key", "value"});
  request.mutable_update_mask()->add_paths("labels");
  request_config->set_etag(config->etag());
  request.set_validate_only(false);
  auto updated_config = client.UpdateInstanceConfig(request).get();
  if (!updated_config) throw std::move(updated_config).status();
  std::cout << "Updated instance config [" << config_id << "]:\n"
            << updated_config->DebugString();
}

C#

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Google.Cloud.Spanner.Admin.Instance.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;

public class UpdateInstanceConfigAsyncSample
{
    public async Task<Operation<InstanceConfig, UpdateInstanceConfigMetadata>> UpdateInstanceConfigAsync(string projectId, string instanceConfigId)
    {
        InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();
        var instanceConfigName = new InstanceConfigName(projectId, instanceConfigId);

        var instanceConfig = new InstanceConfig();
        instanceConfig.InstanceConfigName  = instanceConfigName;

        instanceConfig.DisplayName = "New display name";
        instanceConfig.Labels.Add(new Dictionary<string, string>
        {
            {"cloud_spanner_samples","true"},
            {"updated","true"},
        });

        var updateInstanceConfigOperation = await instanceAdminClient.UpdateInstanceConfigAsync(new UpdateInstanceConfigRequest
        {
            InstanceConfig = instanceConfig,
            UpdateMask = new FieldMask
            {
                Paths = { "display_name", "labels" }
            }
        });

        updateInstanceConfigOperation = await updateInstanceConfigOperation.PollUntilCompletedAsync(); 

        if (updateInstanceConfigOperation.IsFaulted)
        {
            throw updateInstanceConfigOperation.Exception;
        }

        Console.WriteLine("Update Instance Config operation completed successfully.");
        return updateInstanceConfigOperation;
    }
}

Go

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


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

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
	"google.golang.org/genproto/protobuf/field_mask"
)

// updateInstanceConfig updates the custom spanner instance config
func updateInstanceConfig(w io.Writer, projectID, userConfigID string) error {
	// projectID := "my-project-id"
	// userConfigID := "custom-config", custom config names must start with the prefix “custom-”.

	// Add timeout to context.
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()

	adminClient, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer adminClient.Close()
	config, err := adminClient.GetInstanceConfig(ctx, &instancepb.GetInstanceConfigRequest{
		Name: fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, userConfigID),
	})
	if err != nil {
		return fmt.Errorf("updateInstanceConfig.GetInstanceConfig: %w", err)
	}
	config.DisplayName = "updated custom instance config"
	config.Labels["updated"] = "true"
	op, err := adminClient.UpdateInstanceConfig(ctx, &instancepb.UpdateInstanceConfigRequest{
		InstanceConfig: config,
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"display_name", "labels"},
		},
		ValidateOnly: false,
	})
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Waiting for update operation on %s to complete...\n", userConfigID)
	// Wait for the instance configuration creation to finish.
	i, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Waiting for instance config creation to finish failed: %w", err)
	}
	// The instance configuration may not be ready to serve yet.
	if i.State != instancepb.InstanceConfig_READY {
		fmt.Fprintf(w, "InstanceConfig state is not READY yet. Got state %v\n", i.State)
	}
	fmt.Fprintf(w, "Updated instance configuration [%s]\n", config.Name)
	return nil
}

Java

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.FieldMask;
import com.google.spanner.admin.instance.v1.InstanceConfig;
import com.google.spanner.admin.instance.v1.InstanceConfigName;
import com.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

class UpdateInstanceConfigSample {

  static void updateInstanceConfig() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceConfigId = "custom-instance-config";
    updateInstanceConfig(projectId, instanceConfigId);
  }

  static void updateInstanceConfig(String projectId, String instanceConfigId) {
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .build()
            .getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {
      final InstanceConfigName instanceConfigName =
          InstanceConfigName.of(projectId, instanceConfigId);
      final InstanceConfig instanceConfig =
          InstanceConfig.newBuilder()
              .setName(instanceConfigName.toString())
              .setDisplayName("updated custom instance config")
              .putLabels("updated", "true").build();
      /**
       * The field mask must always be specified; this prevents any future
       * fields in [InstanceConfig][google.spanner.admin.instance.v1.InstanceConfig]
       * from being erased accidentally by clients that do not know about them.
       */
      final UpdateInstanceConfigRequest updateInstanceConfigRequest =
          UpdateInstanceConfigRequest.newBuilder()
              .setInstanceConfig(instanceConfig)
              .setUpdateMask(
                  FieldMask.newBuilder().addAllPaths(ImmutableList.of("display_name", "labels"))
                      .build()).build();
      try {
        System.out.printf("Waiting for update operation on %s to complete...\n",
            instanceConfigName);
        InstanceConfig instanceConfigResult =
            instanceAdminClient.updateInstanceConfigAsync(
                updateInstanceConfigRequest).get(5, TimeUnit.MINUTES);
        System.out.printf(
            "Updated instance configuration %s with new display name %s\n",
            instanceConfigResult.getName(), instanceConfig.getDisplayName());
      } catch (ExecutionException | TimeoutException e) {
        System.out.printf(
            "Error: Updating instance config %s failed with error message %s\n",
            instanceConfig.getName(), e.getMessage());
        e.printStackTrace();
      } catch (InterruptedException e) {
        System.out.println(
            "Error: Waiting for updateInstanceConfig operation to finish was interrupted");
      }
    }
  }
}

Node.js

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const instanceConfigId = 'custom-my-instance-config-id';
// const projectId = 'my-project-id';

// Imports the Google Cloud client library
const {Spanner, protos} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = spanner.getInstanceAdminClient();

async function updateInstanceConfig() {
  // Updates an instance config
  try {
    console.log(
      `Updating instance config ${instanceAdminClient.instanceConfigPath(
        projectId,
        instanceConfigId
      )}.`
    );
    const [operation] = await instanceAdminClient.updateInstanceConfig({
      instanceConfig: {
        name: instanceAdminClient.instanceConfigPath(
          projectId,
          instanceConfigId
        ),
        displayName: 'updated custom instance config',
        labels: {
          updated: 'true',
          created: Math.round(Date.now() / 1000).toString(), // current time
        },
      },
      // Field mask specifying fields that should get updated in InstanceConfig
      // Only display_name and labels can be updated
      updateMask: (protos.google.protobuf.FieldMask = {
        paths: ['display_name', 'labels'],
      }),
    });
    console.log(
      `Waiting for update operation for ${instanceConfigId} to complete...`
    );
    await operation.promise();
    console.log(`Updated instance config ${instanceConfigId}.`);
  } catch (err) {
    console.error(
      'ERROR: Updating instance config ',
      instanceConfigId,
      ' failed with error message ',
      err
    );
  }
}
updateInstanceConfig();

PHP

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;
use Google\Cloud\Spanner\Admin\Instance\V1\InstanceConfig;
use Google\Cloud\Spanner\Admin\Instance\V1\UpdateInstanceConfigRequest;
use Google\Protobuf\FieldMask;

/**
 * Updates a customer managed instance configuration.
 * Example:
 * ```
 * update_instance_config($instanceConfigId);
 * ```
 *
 * @param string $projectId The Google Cloud project ID.
 * @param string $instanceConfigId The customer managed instance configuration id. The id must start with 'custom-'.
 */
function update_instance_config(string $projectId, string $instanceConfigId): void
{
    $instanceAdminClient = new InstanceAdminClient();

    $instanceConfigPath = $instanceAdminClient->instanceConfigName($projectId, $instanceConfigId);
    $displayName = 'New display name';

    $instanceConfig = new InstanceConfig();
    $instanceConfig->setName($instanceConfigPath);
    $instanceConfig->setDisplayName($displayName);
    $instanceConfig->setLabels(['cloud_spanner_samples' => true, 'updated' => true]);

    $fieldMask = new FieldMask();
    $fieldMask->setPaths(['display_name', 'labels']);

    $updateInstanceConfigRequest = (new UpdateInstanceConfigRequest())
        ->setInstanceConfig($instanceConfig)
        ->setUpdateMask($fieldMask);

    $operation = $instanceAdminClient->updateInstanceConfig($updateInstanceConfigRequest);

    print('Waiting for operation to complete...' . PHP_EOL);
    $operation->pollUntilComplete();

    printf('Updated instance configuration %s' . PHP_EOL, $instanceConfigId);
}

Python

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

def update_instance_config(user_config_name):
    """Updates the user-managed instance configuration."""

    # user_config_name = `custom-nam11`
    spanner_client = spanner.Client()
    config = spanner_client.instance_admin_api.get_instance_config(
        name="{}/instanceConfigs/{}".format(
            spanner_client.project_name, user_config_name
        )
    )
    config.display_name = "updated custom instance config"
    config.labels["updated"] = "true"
    operation = spanner_client.instance_admin_api.update_instance_config(
        instance_config=config,
        update_mask=field_mask_pb2.FieldMask(paths=["display_name", "labels"]),
    )
    print("Waiting for operation to complete...")
    operation.result(OPERATION_TIMEOUT_SECONDS)
    print("Updated instance configuration {}".format(user_config_name))

Ruby

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

require "google/cloud/spanner"
require "google/cloud/spanner/admin/instance"

def spanner_update_instance_config user_config_id:
  # user_config_id = "The customer managed instance configuration ID, e.g projects/<project>/instanceConfigs/custom-nam11"

  instance_admin_client = Google::Cloud::Spanner::Admin::Instance.instance_admin
  config = instance_admin_client.get_instance_config name: user_config_id
  config.display_name = "updated custom instance config"
  config.labels["updated"] = "true"
  request = {
    instance_config: config,
    update_mask: { paths: ["display_name", "labels"] },
    validate_only: false
  }
  job = instance_admin_client.update_instance_config request

  puts "Waiting for update instance config operation to complete"

  job.wait_until_done!

  if job.error?
    puts job.error
  else
    puts "Updated instance configuration #{config.name}"
  end
end

Excluir uma configuração de instância personalizada

Para excluir uma configuração de instância personalizada, primeiro exclua qualquer instância na configuração da instância.

gcloud

Use o comando gcloud spanner instance-configs delete, substituindo CUSTOM-INSTANCE-CONFIG-ID pelo ID de configuração da instância personalizada:

gcloud spanner instance-configs delete CUSTOM-INSTANCE-CONFIG-ID

C++

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

void DeleteInstanceConfig(
    google::cloud::spanner_admin::InstanceAdminClient client,
    std::string const& project_id, std::string const& config_id) {
  auto project = google::cloud::Project(project_id);
  auto config_name = project.FullName() + "/instanceConfigs/" + config_id;
  auto status = client.DeleteInstanceConfig(config_name);
  if (!status.ok()) throw std::move(status);
  std::cout << "Instance config " << config_name << " successfully deleted\n";
}

C#

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


using System;
using System.Threading.Tasks;
using Google.Cloud.Spanner.Admin.Instance.V1;
using Grpc.Core;

public class DeleteInstanceConfigAsyncSample
{

    public async Task DeleteInstanceConfigAsync(string projectId, string instanceConfigId)
    {
        InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();
        var instanceConfigName = new InstanceConfigName(projectId, instanceConfigId);

        try
        {
            await instanceAdminClient.DeleteInstanceConfigAsync(new DeleteInstanceConfigRequest
            {
                InstanceConfigName = instanceConfigName
            });
        }
        catch (RpcException ex) when (ex.Status.StatusCode == StatusCode.NotFound)
        {
            Console.WriteLine("The specified instance config does not exist. It cannot be deleted.");
            return;
        }

        Console.WriteLine("Delete Instance Config operation is completed");
    }
}

Go

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
)

// deleteInstanceConfig deletes the custom spanner instance config
func deleteInstanceConfig(w io.Writer, projectID, userConfigID string) error {
	// projectID := "my-project-id"
	// userConfigID := "custom-config", custom config names must start with the prefix “custom-”.

	ctx := context.Background()
	adminClient, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer adminClient.Close()
	err = adminClient.DeleteInstanceConfig(ctx, &instancepb.DeleteInstanceConfigRequest{
		Name: fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, userConfigID),
	})
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Deleted instance configuration [%s]\n", userConfigID)
	return nil
}

Java

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest;
import com.google.spanner.admin.instance.v1.InstanceConfigName;

class DeleteInstanceConfigSample {

  static void deleteInstanceConfig() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceConfigId = "custom-user-config";
    deleteInstanceConfig(projectId, instanceConfigId);
  }

  static void deleteInstanceConfig(String projectId, String instanceConfigId) {
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .build()
            .getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {
      final InstanceConfigName instanceConfigName = InstanceConfigName.of(projectId,
          instanceConfigId);
      final DeleteInstanceConfigRequest request =
          DeleteInstanceConfigRequest.newBuilder().setName(instanceConfigName.toString()).build();

      try {
        System.out.printf("Deleting %s...\n", instanceConfigName);
        instanceAdminClient.deleteInstanceConfig(request);
        System.out.printf("Deleted instance configuration %s\n", instanceConfigName);
      } catch (SpannerException e) {
        System.out.printf(
            "Error: Deleting instance configuration %s failed with error message: %s\n",
            instanceConfigName, e.getMessage());
      }
    }
  }
}

Node.js

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const instanceConfigId = 'custom-my-instance-config-id';
// const projectId = 'my-project-id';

// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = spanner.getInstanceAdminClient();

async function deleteInstanceConfig() {
  // Deletes an instance config.

  try {
    // Delete the instance config.
    console.log(`Deleting ${instanceConfigId}...\n`);
    await instanceAdminClient.deleteInstanceConfig({
      name: instanceAdminClient.instanceConfigPath(
        projectId,
        instanceConfigId
      ),
    });
    console.log(`Deleted instance config ${instanceConfigId}.\n`);
  } catch (err) {
    console.error(
      'ERROR: Deleting instance config ',
      instanceConfigId,
      ' failed with error message ',
      err
    );
  }
}
deleteInstanceConfig();

PHP

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;
use Google\Cloud\Spanner\Admin\Instance\V1\DeleteInstanceConfigRequest;

/**
 * Deletes a customer managed instance configuration.
 * Example:
 * ```
 * delete_instance_config($instanceConfigId);
 * ```
 *
 * @param string $projectId The Google Cloud Project ID.
 * @param string $instanceConfigId The customer managed instance configuration id. The id must start with 'custom-'.
 */
function delete_instance_config(string $projectId, string $instanceConfigId)
{
    $instanceAdminClient = new InstanceAdminClient();
    $instanceConfigName = $instanceAdminClient->instanceConfigName(
        $projectId,
        $instanceConfigId
    );

    $request = new DeleteInstanceConfigRequest();
    $request->setName($instanceConfigName);

    $instanceAdminClient->deleteInstanceConfig($request);
    printf('Deleted instance configuration %s' . PHP_EOL, $instanceConfigId);
}

Python

Para saber como instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

def delete_instance_config(user_config_id):
    """Deleted the user-managed instance configuration."""
    spanner_client = spanner.Client()
    spanner_client.instance_admin_api.delete_instance_config(name=user_config_id)
    print("Instance config {} successfully deleted".format(user_config_id))

Ruby

Para aprender a instalar e usar a biblioteca de cliente do Spanner, consulte Bibliotecas de cliente do Spanner.

require "google/cloud/spanner"
require "google/cloud/spanner/admin/instance"

def spanner_delete_instance_config user_config_id:
  # user_config_id = "The customer managed instance configuration ID, e.g projects/<project>/instanceConfigs/custom-nam11"

  instance_admin_client = Google::Cloud::Spanner::Admin::Instance.instance_admin
  instance_admin_client.delete_instance_config name: user_config_id
  puts "Deleted instance configuration #{user_config_id}"
end

A seguir