Create and manage instances Stay organized with collections Save and categorize content based on your preferences.
This page describes how to create, list, edit, and delete Spannerinstances.
Note: To explore Spanner using a 90-day free trial instance,seeCreate a Spanner free trial instance.Create an instance
You can create an instance with the Google Cloud console, theGoogle Cloud CLI, or client libraries. You can also create aninstance with acustom instance configurationby adding optionalread-only replicas.
Note: You don't need to provision storage in Spanner, and youare billed only for the storage that you use. Learn more aboutstorage pricing.Console
In the Google Cloud console, go to theSpanner Instances page.
ClickCreate instance.
In theSelect an edition section, select a Spanneredition.
If you want to compare the specifications between the differenteditions, then clickCompare editions. For moreinformation, see theSpanner editions overview.
ClickContinue.
In theName your instance section, enter anInstance name todisplay in the Google Cloud console. The instance name must be uniquewithin your Google Cloud project.
Enter anInstance ID to permanently identify your instance. Theinstance ID must also be unique within your Google Cloud project.You can't change the instance ID later.
ClickContinue.
In theConfigure your instance section, underChoose a configuration, selectRegional,Dual-region, orMulti-region.
Note: Dual-region and multi-region instance configurations are onlyavailable in the Enterprise Plus edition. If you want tocompare the specifications between the three configurations, then clickCompare region configurations.Select a configuration location from the drop-down.
Optional: To add a read-only replica to a Spanner baseconfiguration, firstcreate a custom instance configuration using theGoogle Cloud CLI.Adding optional read-only replicas to a base configuration is availablein theEnterprise edition and Enterprise Plus edition.
ClickContinue.
In theAllocate compute capacity section, underSelect unit,click one of the following:
- Nodes for large instances. A node is 1000 processing units.
- Processing units for small instances.
For more information, seeCompute capacity, nodes and processing units.
UnderChoose a scaling mode, click one of the following:
Manual allocation if you want to manually set compute capacityfor fixed compute resources and costs.
- Quantity indicates the number of processing units or nodesto use for this instance.
Autoscaling to let Spanner automatically add andremove compute capacity. Managed autoscaler is available in theSpanner Enterprise edition and Enterprise Plus edition.For more information about the managed autoscaler, seeManaged autoscaler for Spanner.Configure the following managed autoscaler options:
- Minimum indicates the minimum limit to scale down to,depending on the measurement unit that you choose forComputecapacity. For more information, seeDetermine the minimum limit.
- Maximum indicates the maximum limit to scale up to,depending on the measurement unit that you choose forComputecapacity. For more information, seeDetermine the maximum limit.
- High priority CPU utilization target indicates the targetpercentage of high priority CPU to use. For more information,seeDetermine the CPU utilization target.
- Storage utilization target indicates the target percentageof storage to use. For more information, seeDetermine the Storage Utilization Target.
Optional: If you selectAutoscaling as the scaling mode, you canclick theShow asymmetric autoscaling options dropdown to autoscaleyour read-only replicas independently from other replicas. For moreinformation, seeAsymmetric read-only autoscaling.
Select the read-only replica you want to asymmetrically autoscale.
Configure the following asymmetric autoscaler options:
- Minimum indicates the minimum limit to scale down to,depending on the measurement unit that you choose forComputecapacity. For more information, seeDetermine the minimum limit.
- Maximum indicates the maximum limit to scale up to,depending on the measurement unit that you choose forComputecapacity. For more information, seeDetermine the maximum limit.
- High priority CPU utilization target indicates the targetpercentage of high priority CPU to use. For more information,seeDetermine the CPU utilization target.
UnderBackups, theEnable default backup schedules checkbox ischecked by default. To disable default backup schedules, uncheck thecheckbox. When enabled, all new databases in the instance have fullbackups created every 24 hours. These backups are retained for 7 days.You can edit or delete the default backup schedules at any time. For moreinformation, seeDefault backup schedules.
ClickCreate to create the instance.
gcloud
Use thegcloud spanner instances createcommand to create an instance. Specify thecompute capacityas the number of nodes or processing units that you want on the instance.
gcloudspannerinstancescreateINSTANCE_ID\--edition=EDITION\--config=INSTANCE_CONFIG\--description=INSTANCE_DESCRIPTION\--default-backup-schedule-type=DEFAULT_BACKUP_SCHEDULE_TYPE\--nodes=NODE_COUNT
or
gcloudspannerinstancescreateINSTANCE_ID\--edition=EDITION\--config=INSTANCE_CONFIG\--description=INSTANCE_DESCRIPTION\--default-backup-schedule-type=DEFAULT_BACKUP_SCHEDULE_TYPE\--processing-units=PROCESSING_UNIT_COUNT
Replace the following:
- INSTANCE-ID: a permanent identifier that is unique withinyour Google Cloud project. You can't change the instance ID later.
- INSTANCE-CONFIG: a permanent identifier of your instanceconfiguration, which defines the geographic location of the instance andaffects how data is replicated. For custom instance configurations, itstarts with
custom-. For more information, seeinstanceconfigurations. - INSTANCE_DESCRIPTION: the name to display for the instance inthe Google Cloud console. The instance name must be unique within yourGoogle Cloud project.
DEFAULT_BACKUP_SCHEDULE_TYPE: the default backup scheduletype that is used in the instance. Must be one of the following values:
AUTOMATIC: a default backup schedule is created automaticallywhen a new database is created in the instance. The default backupschedule creates a full backup every 24 hours. These full backupsare retained for 7 days. You can edit or delete the default backupschedule once it's created.NONE: a default backup schedule isn't created automatically when anew database is created in the instance.
NODE-COUNT: the compute capacity of the instance, expressedas a number of nodes. Each node equals 1000 processing units.
PROCESSING_UNIT_COUNT: the compute capacity of the instance,expressed as a number of processing units. Enter quantities up to 1000in multiples of 100 (100, 200, 300 and so on) and enter greaterquantities in multiples of 1000 (1000, 2000, 3000 and so on). Note:Don't use this parameter if you're creating an instance that you intendto enable with the managed autoscaler later.
Add managed autoscaling
You can also createEnterprise edition andEnterprise Plus editioninstances to use managed autoscaling with thegcloud spanner instances createcommand. For more information, seeManaged autoscaler for Spanner.
Use the following command to create an instance with managed autoscaler.
gcloud spanner instances createINSTANCE_ID \ --edition=EDITION \ --config=INSTANCE_CONFIG \ --description=INSTANCE_DESCRIPTION \ --autoscaling-min-processing-units=MINIMUM_PROCESSING_UNITS \ --autoscaling-max-processing-units=MAXIMUM_PROCESSING_UNITS \ --autoscaling-high-priority-cpu-target=CPU_PERCENTAGE \ --autoscaling-storage-target=STORAGE_PERCENTAGE \ [--asymmetric-autoscaling-option \ location=ASYMMETRIC_AUTOSCALING_LOCATION,min_nodes=ASYMMETRIC_AUTOSCALING_MIN,\ max_nodes=ASYMMETRIC_AUTOSCALING_MAX,high_priority_cpu_target=ASYMMETRIC_CPU_TARGET]
or
gcloud spanner instances createINSTANCE_ID \ --edition=EDITION \ --config=INSTANCE_CONFIG \ --description=INSTANCE_DESCRIPTION \ --autoscaling-min-nodes=MINIMUM_NODES \ --autoscaling-max-nodes=MAXIMUM_NODES \ --autoscaling-high-priority-cpu-target=CPU_PERCENTAGE \ --autoscaling-storage-target=STORAGE_PERCENTAGE \ [--asymmetric-autoscaling-option \ location=ASYMMETRIC_AUTOSCALING_LOCATION,min_nodes=ASYMMETRIC_AUTOSCALING_MIN,\ max_nodes=ASYMMETRIC_AUTOSCALING_MAX,high_priority_cpu_target=ASYMMETRIC_CPU_TARGET]
Replace the following:
- INSTANCE-ID: a permanent identifier that is unique withinyour Google Cloud project. You can't change the instance ID later.
- INSTANCE-CONFIG: a permanent identifier of your instanceconfiguration, which defines the geographic location of the instance andaffects how data is replicated. For custom instance configurations, itstarts with
custom-. For more information, seeinstanceconfigurations. - INSTANCE-DESCRIPTION: the name to display for the instance inthe Google Cloud console. The instance name must be unique within yourGoogle Cloud project.
- MINIMUM_PROCESSING_UNITS,MINIMUM_NODES: theminimum number of processing units or nodes when scaling down. For moreinformation, seeDetermine the minimum limit.
- MAXIMUM_PROCESSING_UNITS,MAXIMUM_NODES: themaximum number of processing units or nodes when scaling up. For moreinformation, seeDetermine the maximum limit.
- CPU_PERCENTAGE: the target percentage of high priority CPU touse, from 10 to 90%. If you're optimizing for cost, then use a higherpercentage. For more information, seeDetermine the CPU utilization target.
- STORAGE_PERCENTAGE: the target percentage of storage to use,from 10 to 99%. For more information, seeDetermine the storage utilization target.
Optional flags:
--asymmetric-autoscaling-option: use this flag to enableasymmetric autoscaling.Replace the following parameters:- ASYMMETRIC_AUTOSCALING_LOCATION: if the flag is used, thenthis parameter is required. The location ofthe read-only region that you want to scale asymmetrically.
- ASYMMETRIC_AUTOSCALING_MIN: optional parameter. The minimumnumber of nodes when scaling down.
- ASYMMETRIC_AUTOSCALING_MAX: optional parameter. The maximumnumber of nodes when scaling up.
- ASYMMETRIC_CPU_TARGET: optional parameter. The targetpercentage of high priority CPU to use, from 10 to 90%. If you'reoptimizing for cost, then use a higher percentage.
Examples for using custom configurations
To create an instancetest-instance in the base regional instanceconfigurationus-central1, run:
gcloud spanner instances create test-instance --edition=STANDARD --config=regional-us-central1 \ --description="Test Instance" --nodes=1To create an instancecustom-eur6-instance in the custom multi-regioninstance configurationcustom-eur6, firstcreate a custom instance configuration.
Then, run:
gcloud spanner instances create custom-eur6-instance --edition=ENTERPRISE_PLUS --config=custom-eur6 \ --description="Instance with custom read-only" --nodes=1You should see a message similar to the following example after runningeither one of the previous commands:
Creating instance...done.
C++
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
voidCreateInstance(google::cloud::spanner_admin::InstanceAdminClientclient,std::stringconst&project_id,std::stringconst&instance_id,std::stringconst&display_name,std::stringconst&config_id){namespacespanner=::google::cloud::spanner;spanner::Instancein(project_id,instance_id);autoproject=google::cloud::Project(project_id);std::stringconfig_name=project.FullName()+"/instanceConfigs/"+config_id;autoinstance=client.CreateInstance(spanner::CreateInstanceRequestBuilder(in,config_name).SetDisplayName(display_name).SetNodeCount(1).SetLabels({{"cloud_spanner_samples", "true"}}).Build()).get();if(!instance)throwstd::move(instance).status();std::cout <<"Created instance [" <<in <<"]:\n" <<instance->DebugString();}C#
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
usingGoogle.Api.Gax.ResourceNames;usingGoogle.Cloud.Spanner.Admin.Instance.V1;usingGoogle.Cloud.Spanner.Common.V1;usingGoogle.LongRunning;usingSystem;usingSystem.Threading.Tasks;publicclassCreateInstanceAsyncSample{publicasyncTask<Instance>CreateInstanceAsync(stringprojectId,stringinstanceId,Instance.Types.Editionedition=Instance.Types.Edition.Standard){// Create the InstanceAdminClient instance.InstanceAdminClientinstanceAdminClient=awaitInstanceAdminClient.CreateAsync();// Initialize request parameters.Instanceinstance=newInstance{InstanceName=InstanceName.FromProjectInstance(projectId,instanceId),ConfigAsInstanceConfigName=InstanceConfigName.FromProjectInstanceConfig(projectId,"regional-us-central1"),DisplayName="This is a display name.",NodeCount=1,Labels={{"cloud_spanner_samples","true"},},Edition=edition,};ProjectNameprojectName=ProjectName.FromProject(projectId);// Make the CreateInstance request.Operation<Instance,CreateInstanceMetadata>response=awaitinstanceAdminClient.CreateInstanceAsync(projectName,instanceId,instance);Console.WriteLine("Waiting for the operation to finish.");// Poll until the returned long-running operation is complete.Operation<Instance,CreateInstanceMetadata>completedResponse=awaitresponse.PollUntilCompletedAsync();if(completedResponse.IsFaulted){Console.WriteLine($"Error while creating instance: {completedResponse.Exception}");throwcompletedResponse.Exception;}Console.WriteLine($"Instance created successfully.");returncompletedResponse.Result;}}Create an instance without a default backup schedule
usingGoogle.Api.Gax.ResourceNames;usingGoogle.Cloud.Spanner.Admin.Instance.V1;usingGoogle.Cloud.Spanner.Common.V1;usingGoogle.LongRunning;usingSystem;usingSystem.Threading.Tasks;publicclassCreateInstanceWithoutDefaultBackupSchedulesAsyncSample{publicasyncTask<Instance>CreateInstanceWithoutDefaultBackupSchedulesAsync(stringprojectId,stringinstanceId){// Create the InstanceAdminClient instance.InstanceAdminClientinstanceAdminClient=awaitInstanceAdminClient.CreateAsync();// Initialize request parameters.Instanceinstance=newInstance{InstanceName=InstanceName.FromProjectInstance(projectId,instanceId),ConfigAsInstanceConfigName=InstanceConfigName.FromProjectInstanceConfig(projectId,"regional-me-central2"),DisplayName="This is a display name.",NodeCount=1,Labels={{"cloud_spanner_samples","true"},},DefaultBackupScheduleType=Instance.Types.DefaultBackupScheduleType.None,};ProjectNameprojectName=ProjectName.FromProject(projectId);// Make the CreateInstance request.Operation<Instance,CreateInstanceMetadata>response=awaitinstanceAdminClient.CreateInstanceAsync(projectName,instanceId,instance);Console.WriteLine("Waiting for the operation to finish.");// Poll until the returned long-running operation is complete.Operation<Instance,CreateInstanceMetadata>completedResponse=awaitresponse.PollUntilCompletedAsync();if(completedResponse.IsFaulted){Console.WriteLine($"Error while creating instance: {completedResponse.Exception}");throwcompletedResponse.Exception;}Console.WriteLine($"Instance created successfully.");returncompletedResponse.Result;}}Go
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
import("context""fmt""io"instance"cloud.google.com/go/spanner/admin/instance/apiv1""cloud.google.com/go/spanner/admin/instance/apiv1/instancepb")funccreateInstance(wio.Writer,projectID,instanceIDstring)error{// projectID := "my-project-id"// instanceID := "my-instance"ctx:=context.Background()instanceAdmin,err:=instance.NewInstanceAdminClient(ctx)iferr!=nil{returnerr}deferinstanceAdmin.Close()op,err:=instanceAdmin.CreateInstance(ctx,&instancepb.CreateInstanceRequest{Parent:fmt.Sprintf("projects/%s",projectID),InstanceId:instanceID,Instance:&instancepb.Instance{Config:fmt.Sprintf("projects/%s/instanceConfigs/%s",projectID,"regional-us-central1"),DisplayName:instanceID,NodeCount:1,Labels:map[string]string{"cloud_spanner_samples":"true"},Edition:instancepb.Instance_STANDARD,},})iferr!=nil{returnfmt.Errorf("could not create instance %s: %w",fmt.Sprintf("projects/%s/instances/%s",projectID,instanceID),err)}// Wait for the instance creation to finish.i,err:=op.Wait(ctx)iferr!=nil{returnfmt.Errorf("waiting for instance creation to finish failed: %w",err)}// The instance may not be ready to serve yet.ifi.State!=instancepb.Instance_READY{fmt.Fprintf(w,"instance state is not READY yet. Got state %v\n",i.State)}fmt.Fprintf(w,"Created instance [%s]\n",instanceID)returnnil}Create an instance with managed autoscaling using Go
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/genproto/protobuf/field_mask")// Example of creating an autoscaling instance with Go.// projectID is the ID of the project that the new instance will be in.// instanceID is the ID of the new instance to be created.funccreateInstanceWithAutoscalingConfig(wio.Writer,projectID,instanceIDstring)error{// projectID := "my-project-id"// instanceID := "my-instance"ctx:=context.Background()instanceAdmin,err:=instance.NewInstanceAdminClient(ctx)iferr!=nil{returnfmt.Errorf("could not create instance admin client for project %s: %w",projectID,err)}deferinstanceAdmin.Close()instanceName:=fmt.Sprintf("projects/%s/instances/%s",projectID,instanceID)fmt.Fprintf(w,"Creating instance %s.",instanceName)op,err:=instanceAdmin.CreateInstance(ctx,&instancepb.CreateInstanceRequest{Parent:fmt.Sprintf("projects/%s",projectID),InstanceId:instanceID,Instance:&instancepb.Instance{Config:fmt.Sprintf("projects/%s/instanceConfigs/%s",projectID,"regional-us-central1"),DisplayName:"Create instance example",AutoscalingConfig:&instancepb.AutoscalingConfig{AutoscalingLimits:&instancepb.AutoscalingConfig_AutoscalingLimits{MinLimit:&instancepb.AutoscalingConfig_AutoscalingLimits_MinNodes{MinNodes:1,},MaxLimit:&instancepb.AutoscalingConfig_AutoscalingLimits_MaxNodes{MaxNodes:2,},},AutoscalingTargets:&instancepb.AutoscalingConfig_AutoscalingTargets{HighPriorityCpuUtilizationPercent:65,StorageUtilizationPercent:95,},},Labels:map[string]string{"cloud_spanner_samples":"true"},Edition:instancepb.Instance_ENTERPRISE_PLUS,},})iferr!=nil{returnfmt.Errorf("could not create instance %s: %w",instanceName,err)}fmt.Fprintf(w,"Waiting for operation on %s to complete...",instanceID)// Wait for the instance creation to finish.i,err:=op.Wait(ctx)iferr!=nil{returnfmt.Errorf("waiting for instance creation to finish failed: %w",err)}// The instance may not be ready to serve yet.ifi.State!=instancepb.Instance_READY{fmt.Fprintf(w,"instance state is not READY yet. Got state %v\n",i.State)}fmt.Fprintf(w,"Created instance [%s].\n",instanceID)instance,err:=instanceAdmin.GetInstance(ctx,&instancepb.GetInstanceRequest{Name:instanceName,// Get the autoscaling_config field from the newly created instance.FieldMask:&field_mask.FieldMask{Paths:[]string{"autoscaling_config"}},})iferr!=nil{returnfmt.Errorf("failed to get instance [%s]: %w",instanceName,err)}fmt.Fprintf(w,"Instance %s has autoscaling_config: %s.",instanceID,instance.AutoscalingConfig)returnnil}Create an instance with asymmetric read-only autoscaling using Go
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/genproto/protobuf/field_mask")// createInstanceWithAsymmetricAutoscalingConfig is a code snippet to show// an example of creating an asymmetric autoscaling enabled instance in Go.//// projectID is the ID of the project that the new instance will be in.// instanceID is the ID of the new instance to be created.funccreateInstanceWithAsymmetricAutoscalingConfig(wio.Writer,projectID,instanceIDstring)error{ctx:=context.Background()instanceAdmin,err:=instance.NewInstanceAdminClient(ctx)iferr!=nil{returnfmt.Errorf("could not create instance admin client for project %s: %w",projectID,err)}deferinstanceAdmin.Close()instanceName:=fmt.Sprintf("projects/%s/instances/%s",projectID,instanceID)fmt.Fprintf(w,"Creating instance %s.",instanceName)op,err:=instanceAdmin.CreateInstance(ctx,&instancepb.CreateInstanceRequest{Parent:fmt.Sprintf("projects/%s",projectID),InstanceId:instanceID,Instance:&instancepb.Instance{Config:fmt.Sprintf("projects/%s/instanceConfigs/%s",projectID,"nam-eur-asia3"),DisplayName:"Create instance example",AutoscalingConfig:&instancepb.AutoscalingConfig{AutoscalingLimits:&instancepb.AutoscalingConfig_AutoscalingLimits{MinLimit:&instancepb.AutoscalingConfig_AutoscalingLimits_MinNodes{MinNodes:1,},MaxLimit:&instancepb.AutoscalingConfig_AutoscalingLimits_MaxNodes{MaxNodes:10,},},AutoscalingTargets:&instancepb.AutoscalingConfig_AutoscalingTargets{HighPriorityCpuUtilizationPercent:65,StorageUtilizationPercent:95,},// Read-only replicas in europe-west1, europe-west4, and asia-east1 are autoscaled// independly from other replicas based on the usage in the respective region.AsymmetricAutoscalingOptions:[]*instancepb.AutoscalingConfig_AsymmetricAutoscalingOption{&instancepb.AutoscalingConfig_AsymmetricAutoscalingOption{ReplicaSelection:&instancepb.ReplicaSelection{Location:"europe-west1",},},&instancepb.AutoscalingConfig_AsymmetricAutoscalingOption{ReplicaSelection:&instancepb.ReplicaSelection{Location:"europe-west4",},},&instancepb.AutoscalingConfig_AsymmetricAutoscalingOption{ReplicaSelection:&instancepb.ReplicaSelection{Location:"asia-east1",},},},},Labels:map[string]string{"cloud_spanner_samples":"true"},Edition:instancepb.Instance_ENTERPRISE_PLUS,},})iferr!=nil{returnfmt.Errorf("could not create instance %s: %w",instanceName,err)}fmt.Fprintf(w,"Waiting for operation on %s to complete...",instanceID)// Wait for the instance creation to finish.i,err:=op.Wait(ctx)iferr!=nil{returnfmt.Errorf("waiting for instance creation to finish failed: %w",err)}// The instance may not be ready to serve yet.ifi.State!=instancepb.Instance_READY{fmt.Fprintf(w,"instance state is not READY yet. Got state %v\n",i.State)}fmt.Fprintf(w,"Created instance [%s].\n",instanceID)instance,err:=instanceAdmin.GetInstance(ctx,&instancepb.GetInstanceRequest{Name:instanceName,// Get the autoscaling_config field from the newly created instance.FieldMask:&field_mask.FieldMask{Paths:[]string{"autoscaling_config"}},})iferr!=nil{returnfmt.Errorf("failed to get instance [%s]: %w",instanceName,err)}fmt.Fprintf(w,"Instance %s has autoscaling_config: %s.",instanceID,instance.AutoscalingConfig)returnnil}Create an instance without a default backup schedule
import("context""fmt""io"instance"cloud.google.com/go/spanner/admin/instance/apiv1""cloud.google.com/go/spanner/admin/instance/apiv1/instancepb")// createInstanceWithoutDefaultBackupSchedule creates instance with default backup schedule disabled.funccreateInstanceWithoutDefaultBackupSchedule(wio.Writer,projectID,instanceIDstring)error{// projectID := "my-project-id"// instanceID := "my-instance"ctx:=context.Background()instanceAdmin,err:=instance.NewInstanceAdminClient(ctx)iferr!=nil{returnerr}deferinstanceAdmin.Close()// Create an instance without default backup schedule, whicn means no default backup schedule will// be created automatically on creation of a database within the instance.req:=&instancepb.CreateInstanceRequest{Parent:fmt.Sprintf("projects/%s",projectID),InstanceId:instanceID,Instance:&instancepb.Instance{Config:fmt.Sprintf("projects/%s/instanceConfigs/%s",projectID,"regional-us-central1"),DisplayName:instanceID,NodeCount:1,Labels:map[string]string{"cloud_spanner_samples":"true"},DefaultBackupScheduleType:instancepb.Instance_NONE,},}op,err:=instanceAdmin.CreateInstance(ctx,req)iferr!=nil{returnfmt.Errorf("could not create instance %s: %w",fmt.Sprintf("projects/%s/instances/%s",projectID,instanceID),err)}// Wait for the instance creation to finish. For more information about instances, see// https://cloud.google.com/spanner/docs/instances.instance,err:=op.Wait(ctx)iferr!=nil{returnfmt.Errorf("waiting for instance creation to finish failed: %w",err)}// The instance may not be ready to serve yet.ifinstance.State!=instancepb.Instance_READY{fmt.Fprintf(w,"instance state is not READY yet. Got state %v\n",instance.State)}fmt.Fprintf(w,"Created instance [%s]\n",instanceID)returnnil}Java
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;importcom.google.spanner.admin.instance.v1.CreateInstanceRequest;importcom.google.spanner.admin.instance.v1.Instance;importcom.google.spanner.admin.instance.v1.InstanceConfigName;importcom.google.spanner.admin.instance.v1.ProjectName;importjava.util.concurrent.ExecutionException;classCreateInstanceExample{staticvoidcreateInstance(){// TODO(developer): Replace these variables before running the sample.StringprojectId="my-project";StringinstanceId="my-instance";createInstance(projectId,instanceId);}staticvoidcreateInstance(StringprojectId,StringinstanceId){// Set Instance configuration.intnodeCount=2;StringdisplayName="Descriptive name";// Create an Instance object that will be used to create the instance.Instanceinstance=Instance.newBuilder().setDisplayName(displayName).setEdition(Instance.Edition.STANDARD).setNodeCount(nodeCount).setConfig(InstanceConfigName.of(projectId,"regional-us-east4").toString()).build();try(Spannerspanner=SpannerOptions.newBuilder().setProjectId(projectId).build().getService();InstanceAdminClientinstanceAdminClient=spanner.createInstanceAdminClient()){// Wait for the createInstance operation to finish.InstancecreatedInstance=instanceAdminClient.createInstanceAsync(CreateInstanceRequest.newBuilder().setParent(ProjectName.of(projectId).toString()).setInstanceId(instanceId).setInstance(instance).build()).get();System.out.printf("Instance %s was successfully created%n",createdInstance.getName());}catch(ExecutionExceptione){System.out.printf("Error: Creating instance %s failed with error message %s%n",instance.getName(),e.getMessage());}catch(InterruptedExceptione){System.out.println("Error: Waiting for createInstance operation to finish was interrupted");}}}Create an instance with managed autoscaling using Java
importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;importcom.google.spanner.admin.instance.v1.AutoscalingConfig;importcom.google.spanner.admin.instance.v1.CreateInstanceRequest;importcom.google.spanner.admin.instance.v1.Instance;importcom.google.spanner.admin.instance.v1.InstanceConfigName;importcom.google.spanner.admin.instance.v1.ProjectName;importcom.google.spanner.admin.instance.v1.ReplicaSelection;importjava.util.concurrent.ExecutionException;classCreateInstanceWithAsymmetricAutoscalingConfigExample{staticvoidcreateInstance(){// TODO(developer): Replace these variables before running the sample.StringprojectId="my-project";StringinstanceId="my-instance";createInstance(projectId,instanceId);}staticvoidcreateInstance(StringprojectId,StringinstanceId){try(Spannerspanner=SpannerOptions.newBuilder().setProjectId(projectId).build().getService();InstanceAdminClientinstanceAdminClient=spanner.createInstanceAdminClient()){// Set Instance configuration.StringconfigId="nam-eur-asia3";StringdisplayName="Descriptive name";// Create an autoscaling config.// When autoscaling_config is enabled, node_count and processing_units fields// need not be specified.// The read-only replicas listed in the asymmetric autoscaling options scale independently// from other replicas.AutoscalingConfigautoscalingConfig=AutoscalingConfig.newBuilder().setAutoscalingLimits(AutoscalingConfig.AutoscalingLimits.newBuilder().setMinNodes(1).setMaxNodes(2)).setAutoscalingTargets(AutoscalingConfig.AutoscalingTargets.newBuilder().setHighPriorityCpuUtilizationPercent(65).setStorageUtilizationPercent(95)).addAsymmetricAutoscalingOptions(AutoscalingConfig.AsymmetricAutoscalingOption.newBuilder().setReplicaSelection(ReplicaSelection.newBuilder().setLocation("europe-west1"))).addAsymmetricAutoscalingOptions(AutoscalingConfig.AsymmetricAutoscalingOption.newBuilder().setReplicaSelection(ReplicaSelection.newBuilder().setLocation("europe-west4"))).addAsymmetricAutoscalingOptions(AutoscalingConfig.AsymmetricAutoscalingOption.newBuilder().setReplicaSelection(ReplicaSelection.newBuilder().setLocation("asia-east1"))).build();Instanceinstance=Instance.newBuilder().setAutoscalingConfig(autoscalingConfig).setDisplayName(displayName).setConfig(InstanceConfigName.of(projectId,configId).toString()).build();// Creates a new instanceSystem.out.printf("Creating instance %s.%n",instanceId);try{// Wait for the createInstance operation to finish.InstanceinstanceResult=instanceAdminClient.createInstanceAsync(CreateInstanceRequest.newBuilder().setParent(ProjectName.of(projectId).toString()).setInstanceId(instanceId).setInstance(instance).build()).get();System.out.printf("Asymmetric Autoscaling instance %s was successfully created%n",instanceResult.getName());}catch(ExecutionExceptione){System.out.printf("Error: Creating instance %s failed with error message %s%n",instance.getName(),e.getMessage());}catch(InterruptedExceptione){System.out.println("Error: Waiting for createInstance operation to finish was interrupted");}}}}Create an instance with asymmetric read-only autoscaling using Java
importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;importcom.google.spanner.admin.instance.v1.AutoscalingConfig;importcom.google.spanner.admin.instance.v1.CreateInstanceRequest;importcom.google.spanner.admin.instance.v1.Instance;importcom.google.spanner.admin.instance.v1.InstanceConfigName;importcom.google.spanner.admin.instance.v1.ProjectName;importcom.google.spanner.admin.instance.v1.ReplicaSelection;importjava.util.concurrent.ExecutionException;classCreateInstanceWithAsymmetricAutoscalingConfigExample{staticvoidcreateInstance(){// TODO(developer): Replace these variables before running the sample.StringprojectId="my-project";StringinstanceId="my-instance";createInstance(projectId,instanceId);}staticvoidcreateInstance(StringprojectId,StringinstanceId){try(Spannerspanner=SpannerOptions.newBuilder().setProjectId(projectId).build().getService();InstanceAdminClientinstanceAdminClient=spanner.createInstanceAdminClient()){// Set Instance configuration.StringconfigId="nam-eur-asia3";StringdisplayName="Descriptive name";// Create an autoscaling config.// When autoscaling_config is enabled, node_count and processing_units fields// need not be specified.// The read-only replicas listed in the asymmetric autoscaling options scale independently// from other replicas.AutoscalingConfigautoscalingConfig=AutoscalingConfig.newBuilder().setAutoscalingLimits(AutoscalingConfig.AutoscalingLimits.newBuilder().setMinNodes(1).setMaxNodes(2)).setAutoscalingTargets(AutoscalingConfig.AutoscalingTargets.newBuilder().setHighPriorityCpuUtilizationPercent(65).setStorageUtilizationPercent(95)).addAsymmetricAutoscalingOptions(AutoscalingConfig.AsymmetricAutoscalingOption.newBuilder().setReplicaSelection(ReplicaSelection.newBuilder().setLocation("europe-west1"))).addAsymmetricAutoscalingOptions(AutoscalingConfig.AsymmetricAutoscalingOption.newBuilder().setReplicaSelection(ReplicaSelection.newBuilder().setLocation("europe-west4"))).addAsymmetricAutoscalingOptions(AutoscalingConfig.AsymmetricAutoscalingOption.newBuilder().setReplicaSelection(ReplicaSelection.newBuilder().setLocation("asia-east1"))).build();Instanceinstance=Instance.newBuilder().setAutoscalingConfig(autoscalingConfig).setDisplayName(displayName).setConfig(InstanceConfigName.of(projectId,configId).toString()).build();// Creates a new instanceSystem.out.printf("Creating instance %s.%n",instanceId);try{// Wait for the createInstance operation to finish.InstanceinstanceResult=instanceAdminClient.createInstanceAsync(CreateInstanceRequest.newBuilder().setParent(ProjectName.of(projectId).toString()).setInstanceId(instanceId).setInstance(instance).build()).get();System.out.printf("Asymmetric Autoscaling instance %s was successfully created%n",instanceResult.getName());}catch(ExecutionExceptione){System.out.printf("Error: Creating instance %s failed with error message %s%n",instance.getName(),e.getMessage());}catch(InterruptedExceptione){System.out.println("Error: Waiting for createInstance operation to finish was interrupted");}}}}Create an instance without a default backup schedule
importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;importcom.google.spanner.admin.instance.v1.CreateInstanceRequest;importcom.google.spanner.admin.instance.v1.Instance;importcom.google.spanner.admin.instance.v1.InstanceConfigName;importcom.google.spanner.admin.instance.v1.ProjectName;importjava.util.concurrent.ExecutionException;classCreateInstanceWithoutDefaultBackupSchedulesExample{staticvoidcreateInstanceWithoutDefaultBackupSchedules(){// TODO(developer): Replace these variables before running the sample.StringprojectId="my-project";StringinstanceId="my-instance";createInstanceWithoutDefaultBackupSchedules(projectId,instanceId);}staticvoidcreateInstanceWithoutDefaultBackupSchedules(StringprojectId,StringinstanceId){// Set Instance configuration.intnodeCount=2;StringdisplayName="Descriptive name";// Create an Instance object that will be used to create the instance.Instanceinstance=Instance.newBuilder().setDisplayName(displayName).setDefaultBackupScheduleType(Instance.DefaultBackupScheduleType.NONE).setNodeCount(nodeCount).setConfig(InstanceConfigName.of(projectId,"regional-us-east4").toString()).build();try(Spannerspanner=SpannerOptions.newBuilder().setProjectId(projectId).build().getService();InstanceAdminClientinstanceAdminClient=spanner.createInstanceAdminClient()){// Wait for the createInstance operation to finish.InstancecreatedInstance=instanceAdminClient.createInstanceAsync(CreateInstanceRequest.newBuilder().setParent(ProjectName.of(projectId).toString()).setInstanceId(instanceId).setInstance(instance).build()).get();System.out.printf("Instance %s was successfully created%n",createdInstance.getName());}catch(ExecutionExceptione){System.out.printf("Error: Creating instance %s failed with error message %s%n",instance.getName(),e.getMessage());}catch(InterruptedExceptione){System.out.println("Error: Waiting for createInstance operation to finish was interrupted");}}}Node.js
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
// Imports the Google Cloud client libraryconst{Spanner,protos}=require('@google-cloud/spanner');// Creates a clientconstspanner=newSpanner({projectId:projectId,});constinstanceAdminClient=awaitspanner.getInstanceAdminClient();/** * TODO(developer): Uncomment the following lines before running the sample. **/// const projectId = 'my-project-id';// const instanceId = 'my-instance';// Creates a new instancetry{console.log(`Creating instance${instanceAdminClient.instancePath(projectId,instanceId,)}.`,);const[operation]=awaitinstanceAdminClient.createInstance({instanceId:instanceId,parent:instanceAdminClient.projectPath(projectId),instance:{config:instanceAdminClient.instanceConfigPath(projectId,'regional-us-central1',),nodeCount:1,displayName:'Display name for the instance.',labels:{cloud_spanner_samples:'true',created:Math.round(Date.now()/1000).toString(),// current time},edition:protos.google.spanner.admin.instance.v1.Instance.Edition.STANDARD,//optional},});console.log(`Waiting for operation on${instanceId} to complete...`);awaitoperation.promise();console.log(`Created instance${instanceId}.`);}catch(err){console.error('ERROR:',err);}Note: The old client library interface code samples for Node.js are archived inGitHub.
Create an instance with managed autoscaling using Node.js
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
// Imports the Google Cloud client libraryconst{Spanner,protos}=require('@google-cloud/spanner');/** * TODO(developer): Uncomment the following lines before running the sample. */// const projectId = 'my-project-id';// const instanceId = 'my-instance';// Creates a clientconstspanner=newSpanner({projectId:projectId,});// Get the instance admin clientconstinstanceAdminClient=spanner.getInstanceAdminClient();constautoscalingConfig=protos.google.spanner.admin.instance.v1.AutoscalingConfig.create({// Only one of minNodes/maxNodes or minProcessingUnits/maxProcessingUnits can be set.autoscalingLimits:protos.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.create({minNodes:1,maxNodes:2,},),// highPriorityCpuUtilizationPercent and storageUtilizationPercent are both// percentages and must lie between 0 and 100.autoscalingTargets:protos.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.create({highPriorityCpuUtilizationPercent:65,storageUtilizationPercent:95,},),});// Creates a new instance with autoscaling configuration// When autoscalingConfig is enabled, nodeCount and processingUnits fields// need not be specified.try{console.log(`Creating instance${instanceAdminClient.instancePath(projectId,instanceId,)}.`,);const[operation]=awaitinstanceAdminClient.createInstance({instanceId:instanceId,parent:instanceAdminClient.projectPath(projectId),instance:{config:instanceAdminClient.instanceConfigPath(projectId,'regional-us-central1',),displayName:'Display name for the instance.',autoscalingConfig:autoscalingConfig,labels:{cloud_spanner_samples:'true',created:Math.round(Date.now()/1000).toString(),// current time},// Managed autoscaler is available only for ENTERPRISE editionedition:protos.google.spanner.admin.instance.v1.Instance.Edition.ENTERPRISE,},});console.log(`Waiting for operation on${instanceId} to complete...`);awaitoperation.promise();console.log(`Created instance${instanceId}.`);// get instance metadataconst[metadata]=awaitinstanceAdminClient.getInstance({name:instanceAdminClient.instancePath(projectId,instanceId),});console.log(`Autoscaling configurations of${instanceId} are: `+'\n'+`Min nodes:${metadata.autoscalingConfig.autoscalingLimits.minNodes} `+'nodes.'+'\n'+`Max nodes:${metadata.autoscalingConfig.autoscalingLimits.maxNodes}`+' nodes.'+'\n'+`High priority cpu utilization percent:${metadata.autoscalingConfig.autoscalingTargets.highPriorityCpuUtilizationPercent}.`+'\n'+`Storage utilization percent:${metadata.autoscalingConfig.autoscalingTargets.storageUtilizationPercent}.`,);}catch(err){console.error('ERROR:',err);}Create an instance without a default backup schedule
/** * TODO(developer): Uncomment the following lines before running the sample. **/// const projectId = 'my-project-id';// const instanceId = 'my-instance';// Imports the Google Cloud client libraryconst{Spanner,protos}=require('@google-cloud/spanner');// Creates a clientconstspanner=newSpanner({projectId:projectId,});constinstanceAdminClient=awaitspanner.getInstanceAdminClient();// Creates a new instancetry{const[operation]=awaitinstanceAdminClient.createInstance({instanceId:instanceId,parent:instanceAdminClient.projectPath(projectId),instance:{config:instanceAdminClient.instanceConfigPath(projectId,'regional-me-central2',),nodeCount:1,displayName:'Display name for the instance.',labels:{cloud_spanner_samples:'true',created:Math.round(Date.now()/1000).toString(),// current time},defaultBackupScheduleType:protos.google.spanner.admin.instance.v1.Instance.DefaultBackupScheduleType.NONE,},});awaitoperation.promise();console.log(`Created instance${instanceId} without default backup schedules.`,);}catch(err){console.error('ERROR:',err);}PHP
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;use Google\Cloud\Spanner\Admin\Instance\V1\CreateInstanceRequest;use Google\Cloud\Spanner\Admin\Instance\V1\Instance;/** * Creates an instance. * Example: * ``` * create_instance($projectId, $instanceId); * ``` * * @param string $projectId The Spanner project ID. * @param string $instanceId The Spanner instance ID. */function create_instance(string $projectId, string $instanceId): void{ $instanceAdminClient = new InstanceAdminClient(); $parent = InstanceAdminClient::projectName($projectId); $instanceName = InstanceAdminClient::instanceName($projectId, $instanceId); $configName = $instanceAdminClient->instanceConfigName($projectId, 'regional-us-central1'); $instance = (new Instance()) ->setName($instanceName) ->setConfig($configName) ->setDisplayName('dispName') ->setNodeCount(1); $operation = $instanceAdminClient->createInstance( (new CreateInstanceRequest()) ->setParent($parent) ->setInstanceId($instanceId) ->setInstance($instance) ); print('Waiting for operation to complete...' . PHP_EOL); $operation->pollUntilComplete(); printf('Created instance %s' . PHP_EOL, $instanceId);}Note: The old client library interface code samples for PHP are archived inGitHub.
Python
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
defcreate_instance(instance_id):"""Creates an instance."""fromgoogle.cloud.spanner_admin_instance_v1.typesimportspanner_instance_adminspanner_client=spanner.Client()config_name="{}/instanceConfigs/regional-us-central1".format(spanner_client.project_name)operation=spanner_client.instance_admin_api.create_instance(parent=spanner_client.project_name,instance_id=instance_id,instance=spanner_instance_admin.Instance(config=config_name,display_name="This is a display name.",node_count=1,labels={"cloud_spanner_samples":"true","sample_name":"snippets-create_instance-explicit","created":str(int(time.time())),},edition=spanner_instance_admin.Instance.Edition.STANDARD,# Optional),)print("Waiting for operation to complete...")operation.result(OPERATION_TIMEOUT_SECONDS)print("Created instance{}".format(instance_id))Note: The old client library interface code samples for Python are archived inGitHub.
Create an instance with managed autoscaling using Python
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
defcreate_instance_with_autoscaling_config(instance_id):"""Creates a Cloud Spanner instance with an autoscaling configuration."""fromgoogle.cloud.spanner_admin_instance_v1.typesimportspanner_instance_adminspanner_client=spanner.Client()config_name="{}/instanceConfigs/regional-us-central1".format(spanner_client.project_name)autoscaling_config=spanner_instance_admin.AutoscalingConfig(# Only one of minNodes/maxNodes or minProcessingUnits/maxProcessingUnits can be set.autoscaling_limits=spanner_instance_admin.AutoscalingConfig.AutoscalingLimits(min_nodes=1,max_nodes=2,),# highPriorityCpuUtilizationPercent and storageUtilizationPercent are both# percentages and must lie between 0 and 100.autoscaling_targets=spanner_instance_admin.AutoscalingConfig.AutoscalingTargets(high_priority_cpu_utilization_percent=65,storage_utilization_percent=95,),)# Creates a new instance with autoscaling configuration# When autoscalingConfig is enabled, nodeCount and processingUnits fields# need not be specified.request=spanner_instance_admin.CreateInstanceRequest(parent=spanner_client.project_name,instance_id=instance_id,instance=spanner_instance_admin.Instance(config=config_name,display_name="This is a display name.",autoscaling_config=autoscaling_config,labels={"cloud_spanner_samples":"true","sample_name":"snippets-create_instance_with_autoscaling_config","created":str(int(time.time())),},edition=spanner_instance_admin.Instance.Edition.ENTERPRISE,# Optional),)operation=spanner_client.instance_admin_api.create_instance(request=request)print("Waiting for operation to complete...")instance=operation.result(OPERATION_TIMEOUT_SECONDS)print("Created instance{} with{} autoscaling config".format(instance_id,instance.autoscaling_config))Create an instance without a default backup schedule
defcreate_instance_without_default_backup_schedules(instance_id):spanner_client=spanner.Client()config_name="{}/instanceConfigs/regional-me-central2".format(spanner_client.project_name)operation=spanner_client.instance_admin_api.create_instance(parent=spanner_client.project_name,instance_id=instance_id,instance=spanner_instance_admin.Instance(config=config_name,display_name="This is a display name.",node_count=1,default_backup_schedule_type=spanner_instance_admin.Instance.DefaultBackupScheduleType.NONE,# Optional),)print("Waiting for operation to complete...")operation.result(OPERATION_TIMEOUT_SECONDS)print("Created instance{} without default backup schedules".format(instance_id))Ruby
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
# project_id = "Your Google Cloud project ID"# instance_id = "Your Spanner instance ID"# instance_config_id = "Your Spanner InstanceConfig ID"require"google/cloud/spanner"require"google/cloud/spanner/admin/instance"instance_admin_client=Google::Cloud::Spanner::Admin::Instance.instance_adminproject_path=instance_admin_client.project_pathproject:project_idinstance_path=instance_admin_client.instance_pathproject:project_id,instance:instance_idinstance_config_path=instance_admin_client.instance_config_pathproject:project_id,instance_config:instance_config_idjob=instance_admin_client.create_instanceparent:project_path,instance_id:instance_id,instance:{name:instance_path,config:instance_config_path,display_name:instance_id,node_count:2,labels:{cloud_spanner_samples:"true"}}puts"Waiting for create instance operation to complete"job.wait_until_done!ifjob.error?putsjob.errorelseputs"Created instance#{instance_id}"endList instances
You can show a list of your Spanner instances.
Console
Go to theSpanner Instances page in the Google Cloud console.
The Google Cloud console shows a list of your Spannerinstances, along with each instance's ID, display name, configuration, andcompute capacity expressed in both processing units and in nodes.
gcloud
Use thegcloud spanner instances listcommand:
gcloud spanner instances listThe gcloud CLI prints a list of your Spannerinstances, along with each instance's ID, display name, configuration, andcompute capacity.
Edit an instance
The following sections explain how to upgrade the edition of your instance, andchange an instance's display name, compute capacity, and default backup scheduletype. You can't change theinstance ID or instance configuration (however, you canmove your instance).
Upgrade the edition
You can upgrade your Standard edition instances to a higher-tieredition. Standard edition instances can be upgraded to theEnterprise edition or Enterprise Plus edition.Enterprise edition instances can be upgraded to theEnterprise Plus edition. The edition upgrade takes approximately 10minutes to complete with zero downtime.
Console
Go to theSpanner Instances page in the Google Cloud console.
Click the name of the instance that you want to upgrade.
ClickUpgrade next to the edition type.
In theEdition instance page, and underUpdate edition, selectthe new higher-tier edition for your instance.
ClickSave.
gcloud
Use thegcloud spanner instances updatecommand to upgrade your instance's edition:
gcloud spanner instances updateINSTANCE_ID --edition=EDITION \[--async]
Replace the following:
- INSTANCE_ID: the permanent identifier for the instance.
- EDITION: specify the new higher-tier edition for yourinstance. For more information, see theSpanner editions overview.
Optional flags:
--async: Use this flag if you want your request to return immediately,without waiting for the operation in progress to complete. You can checkthe status of your request by runninggcloud spanner operations describe.
Go
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/genproto/protobuf/field_mask")funcupdateInstance(wio.Writer,projectID,instanceIDstring)error{// projectID := "my-project-id"// instanceID := "my-instance"ctx:=context.Background()instanceAdmin,err:=instance.NewInstanceAdminClient(ctx)iferr!=nil{returnerr}deferinstanceAdmin.Close()req:=&instancepb.UpdateInstanceRequest{Instance:&instancepb.Instance{Name:fmt.Sprintf("projects/%s/instances/%s",projectID,instanceID),// The edition selected for this instance.// Different editions provide different capabilities at different price points.// For more information, see https://cloud.google.com/spanner/docs/editions-overview.Edition:instancepb.Instance_ENTERPRISE,},FieldMask:&field_mask.FieldMask{Paths:[]string{"edition"},},}op,err:=instanceAdmin.UpdateInstance(ctx,req)iferr!=nil{returnfmt.Errorf("could not update instance %s: %w",fmt.Sprintf("projects/%s/instances/%s",projectID,instanceID),err)}// Wait for the instance update to finish._,err=op.Wait(ctx)iferr!=nil{returnfmt.Errorf("waiting for instance update to finish failed: %w",err)}fmt.Fprintf(w,"Updated instance [%s]\n",instanceID)returnnil}Java
importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;importcom.google.common.collect.Lists;importcom.google.protobuf.FieldMask;importcom.google.spanner.admin.instance.v1.Instance;importcom.google.spanner.admin.instance.v1.InstanceConfigName;importcom.google.spanner.admin.instance.v1.InstanceName;importcom.google.spanner.admin.instance.v1.UpdateInstanceRequest;importjava.util.concurrent.ExecutionException;publicclassUpdateInstanceExample{staticvoidupdateInstance(){// TODO(developer): Replace these variables before running the sample.StringprojectId="my-project";StringinstanceId="my-instance";updateInstance(projectId,instanceId);}staticvoidupdateInstance(StringprojectId,StringinstanceId){// Set Instance configuration.intnodeCount=2;StringdisplayName="Updated name";// Update an Instance object that will be used to update the instance.Instanceinstance=Instance.newBuilder().setName(InstanceName.of(projectId,instanceId).toString()).setDisplayName(displayName).setNodeCount(nodeCount).setEdition(Instance.Edition.ENTERPRISE).setConfig(InstanceConfigName.of(projectId,"regional-us-east4").toString()).build();try(Spannerspanner=SpannerOptions.newBuilder().setProjectId(projectId).build().getService();InstanceAdminClientinstanceAdminClient=spanner.createInstanceAdminClient()){// Wait for the updatedInstance operation to finish.InstanceupdatedInstance=instanceAdminClient.updateInstanceAsync(UpdateInstanceRequest.newBuilder().setFieldMask(FieldMask.newBuilder().addAllPaths(Lists.newArrayList("edition"))).setInstance(instance).build()).get();System.out.printf("Instance %s was successfully updated%n",updatedInstance.getName());}catch(ExecutionExceptione){System.out.printf("Error: Updating instance %s failed with error message %s%n",instance.getName(),e.getMessage());}catch(InterruptedExceptione){System.out.println("Error: Waiting for updateInstance operation to finish was interrupted");}}}Node.js
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
// Imports the Google Cloud client libraryconst{Spanner,protos}=require('@google-cloud/spanner');/** * TODO(developer): Uncomment the following lines before running the sample. */// const projectId = 'my-project-id';// const instanceId = 'my-instance';// Creates a clientconstspanner=newSpanner({projectId:projectId,});constinstanceAdminClient=spanner.getInstanceAdminClient();// Updates an instancetry{console.log(`Updating instance${instanceAdminClient.instancePath(projectId,instanceId,)}.`,);const[operation]=awaitinstanceAdminClient.updateInstance({instance:{name:instanceAdminClient.instancePath(projectId,instanceId),labels:{updated:'true',created:Math.round(Date.now()/1000).toString(),// current time},edition:protos.google.spanner.admin.instance.v1.Instance.Edition.ENTERPRISE,//optional},// Field mask specifying fields that should get updated in an InstancefieldMask:(protos.google.protobuf.FieldMask={paths:['labels','edition'],}),});console.log(`Waiting for operation on${instanceId} to complete...`);awaitoperation.promise();console.log(`Updated instance${instanceId}.`);const[metadata]=awaitinstanceAdminClient.getInstance({name:instanceAdminClient.instancePath(projectId,instanceId),});console.log(`Instance${instanceId} has been updated with the${metadata.edition} `+'edition.',);}catch(err){console.error('ERROR:',err);}Python
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
defupdate_instance(instance_id):"""Updates an instance."""fromgoogle.cloud.spanner_admin_instance_v1.typesimportspanner_instance_adminspanner_client=spanner.Client()name="{}/instances/{}".format(spanner_client.project_name,instance_id)operation=spanner_client.instance_admin_api.update_instance(instance=spanner_instance_admin.Instance(name=name,labels={"sample_name":"snippets-update_instance-explicit",},edition=spanner_instance_admin.Instance.Edition.ENTERPRISE,# Optional),field_mask=field_mask_pb2.FieldMask(paths=["labels","edition"]),)print("Waiting for operation to complete...")operation.result(900)print("Updated instance{}".format(instance_id))Downgrade the edition
You can downgrade your Spanner instances to a lower-tieredition. You must stop using the higher-tier edition features in order todowngrade. Enterprise edition instances can be downgraded to theStandard edition. Enterprise Plus edition instances can bedowngraded to the Enterprise edition or Standard edition.The edition downgrade takes approximately 10 minutes to complete with zerodowntime.
gcloud
Use thegcloud spanner instances updatecommand to downgrade your instance's edition:
gcloud spanner instances updateINSTANCE_ID --edition=EDITION
Replace the following:
- INSTANCE_ID: the permanent identifier for the instance.
- EDITION: specify the new lower-tier edition for yourinstance. For more information, see theSpanner editions overview.
Change the display name
Console
Go to theSpanner Instances page in the Google Cloud console.
Click the name of the instance that you want to rename.
ClickEdit instance.
Enter a new instance name. This name must be unique within theGoogle Cloud project.
ClickSave.
gcloud
Use thegcloud spanner instances updatecommand:
gcloud spanner instances updateINSTANCE_ID --description=INSTANCE_NAME
Replace the following:
- INSTANCE_ID: the permanent identifier for the instance.
- INSTANCE_NAME: the name to display for the instance in theGoogle Cloud console. The instance name must be unique within yourGoogle Cloud project.
Change the compute capacity
You must provision enoughcompute capacity to keepCPU utilization andstorage utilization below the recommended maximums.For more information, see thequotas and limits forSpanner.
You can reduce the compute capacity of a Spanner instance exceptin the following scenarios:
You can't store more than 10 TiB of data pernode (1000 processing units).
There are a large number ofsplits foryour instance's data. In this scenario, Spanner might not beable to manage the splits after you reduce compute capacity. You can tryreducing the compute capacity by progressively smaller amounts until you findthe minimum capacity that Spanner needs to manage all of theinstance's splits.
Spanner can create a large number of splits to accommodate yourusage patterns. If your usage patterns change, then after one or two weeks,Spanner might merge some splits together and you can try toreduce the instance's compute capacity.
When removing compute capacity, monitor your CPU utilization and requestlatencies inCloud Monitoring to ensure CPUutilization stays under 65% for regionalinstances and 45% for each region inmulti-region instances. You might experience a temporary increase in requestlatencies while removing compute capacity.
If you want to increase the compute capacity of an instance, yourGoogle Cloud project must have sufficient quota to add the computecapacity. The time it takes for the increase request to complete depends on thesize of the request. In most cases, requests complete within a few minutes. Onrare occasions, a scale up might take up to an hour to complete.
Console
Go to theSpanner Instances page in the Google Cloud console.
Click the name of the instance that you want to change.
ClickEdit Instance.
Change the compute capacity by choosing the measurement units(processing units or nodes) and then entering a quantity. When usingprocessing units, enter quantities up to 1000 in multiples of 100 (100,200, 300 and so on) and enter greater quantities in multiples of 1000(1000, 2000, 3000 and so on). Each node equals 1000 processing units.
ClickSave.
If you see a dialog that says you have insufficient quota to add computecapacity in this location, follow the instructions to request a higherquota.
gcloud
Use thegcloud spanner instances updatecommand. When using this command, specify thecompute capacity as anumber of nodes or processing units.
gcloud spanner instances updateINSTANCE_ID --nodes=NODE_COUNT[--async]
or
gcloud spanner instances updateINSTANCE_ID--processing-units=PROCESSING_UNIT_COUNT [--async]
Replace the following:
- INSTANCE_ID: the permanent identifier for the instance.
- NODE_COUNT: the compute capacity of the instance, expressed as anumber of nodes. Each node equals 1000 processing units.
- PROCESSING_UNIT_COUNT: the compute capacity of the instance,expressed as a number of processing units. Enter quantities up to 1000in multiples of 100 (100, 200, 300 and so on) and enter greaterquantities in multiples of 1000 (1000, 2000, 3000 and so on).
Optional flags:
--async: Use this flag if you want your request to return immediately,without waiting for the operation in progress to complete. You can checkthe status of your request by runninggcloud spanner operations describe.
Enable or modify managed autoscaler on an instance
You can enable or modify autoscaling on a Spanner instance usingthe Google Cloud console, thegcloud CLI, or theSpanner client libraries.The following limitations apply when you add or change the managed autoscalingfeature on an existing instance:
- Managed autoscaler is only available in the Enterprise editionor Enterprise Plus edition.
- You can't enable the managed autoscaler on an instance that you are moving.
You can'tmove an instance while the managed autoscaler isenabled.
Console
Go to theSpanner Instances page in the Google Cloud console.
Click the name of the instance that you want to enable the managedautoscaler on.
ClickEdit instance.
UnderConfigure compute capacity, clickAutoscaling.
ForMinimum, select the minimum limit to use when scaling down.For more information, seeDetermine the minimum limit.
ForMaximum, select the maximum limit to use when scaling up. Formore information, seeDetermine the maximum limit.
ForHigh priority CPU utilization target, select the percentage ofhigh priority CPU to use. For more information, seeDetermine the CPU utilization target.
ForStorage utilization target, select the percentage of storage touse. For more information, seeDetermine the storage utilization target.
Optional: If you selectAutoscaling as the scaling mode, then you canclick theShow asymmetric autoscaling options dropdown to autoscaleyour read-only replicas independently from other replicas.
Select the read-only replica you want to asymmetrically autoscale.
Configure the following autoscaler options:
- Minimum indicates the minimum limit to scale down to,depending on the measurement unit that you choose forComputecapacity. For more information, seeDetermine the minimum limit.
- Maximum indicates the maximum limit to scale up to,depending on the measurement unit that you choose forComputecapacity. For more information, seeDetermine the maximum limit.
- High priority CPU utilization target indicates the targetpercentage of high priority CPU to use. For more information,seeDetermine the CPU utilization target.
ClickSave.
gcloud
Use thegcloud spanner instances updatecommand to add the managed autoscaler to an instance. For more information andlimitations, seeGoogle Cloud CLI flags and limitations.
You can add the managed autoscaler with the following command:
gcloud spanner instances updateINSTANCE_ID \ --autoscaling-min-processing-units=MINIMUM_PROCESSING_UNITS \ --autoscaling-max-processing-units=MAXIMUM_PROCESSING_UNITS \ --autoscaling-high-priority-cpu-target=CPU_PERCENTAGE \ --autoscaling-storage-target=STORAGE_PERCENTAGE \ [--asymmetric-autoscaling-option \ location=ASYMMETRIC_AUTOSCALING_LOCATION,min_nodes=ASYMMETRIC_AUTOSCALING_MIN,\ max_nodes=ASYMMETRIC_AUTOSCALING_MAX,high_priority_cpu_target=ASYMMETRIC_CPU_TARGET]
or
gcloud spanner instances updateINSTANCE_ID \ --autoscaling-min-processing-units=MINIMUM_NODES \ --autoscaling-max-processing-units=MAXIMUM_NODES \ --autoscaling-high-priority-cpu-target=CPU_PERCENTAGE \ --autoscaling-storage-target=STORAGE_PERCENTAGE \ [--asymmetric-autoscaling-option \ location=ASYMMETRIC_AUTOSCALING_LOCATION,min_nodes=ASYMMETRIC_AUTOSCALING_MIN,\ max_nodes=ASYMMETRIC_AUTOSCALING_MAX,high_priority_cpu_target=ASYMMETRIC_CPU_TARGET]
Replace the following:
- INSTANCE_ID: the permanent identifier for the instance.
- MINIMUM_PROCESSING_UNITS,MINIMUM_NODES: theminimum number of processing units or nodes to use when scaling down.For more information, seeDetermine the minimum limit.
- MAXIMUM_PROCESSING_UNITS,MAXIMUM_NODES: themaximum number of processing units or nodes to use when scaling up. Formore information, seeDetermine the maximum limit.
- CPU_PERCENTAGE: the target percentage of high priority CPU touse, from 10% to 90%. If you're optimizing for cost and don't require lowlatency on all requests, then use a higher percentage. For moreinformation, seeDetermine the CPU utilization target.
- STORAGE_PERCENTAGE: the target percentage of storage to use,from 10% to 99%. For more information, seeDetermine the Storage Utilization Target.
Optional flags:
--asymmetric-autoscaling-option: Use this flag to enableasymmetric autoscaling.Replace the following parameters:- ASYMMETRIC_AUTOSCALING_LOCATION: if the flag is used, thenthis parameter is required. The location ofthe read-only region that you want to scale asymmetrically.
- ASYMMETRIC_AUTOSCALING_MIN: optional parameter. The minimumnumber of nodes when scaling down.
- ASYMMETRIC_AUTOSCALING_MAX: optional parameter. The maximumnumber of nodes when scaling up.
- ASYMMETRIC_CPU_TARGET: optional parameter. The targetpercentage of high priority CPU to use, from 10 to 90%. If you'reoptimizing for cost, then use a higher percentage.
After you add the managed autoscaler to an instance, you can also modify themanaged autoscaler settings. For example, if you want to increase the maximumnumber of processing units to 10000, run the following command:
gcloud spanner instances update test-instance \ --autoscaling-max-processing-units=10000Change an instance from using managed autoscaler to manual scaling
You can change whether a Spanner instance uses manual ormanaged scaling by using the Google Cloud console, thegcloud CLI, or theSpanner client libraries.
Console
Go to theSpanner Instances page in the Google Cloud console.
Click the name of the instance that you want to disable managedautoscaler on.
UnderChoose a scaling mode, clickManual allocation.
ClickSave.
gcloud
Use thegcloud spanner instances updatecommand to update the instance.
Use the following command to change an instance from using the managedautoscaler to manual scaling:
gcloud spanner instances updateINSTANCE_ID \ --processing-units=PROCESSING_UNIT_COUNT
or
gcloud spanner instances updateINSTANCE_ID \ --nodes=NODE_COUNT
Replace the following:
- INSTANCE_ID: the permanent identifier for the instance.
- NODE_COUNT: the compute capacity of the instance, expressedas a number of nodes. Each node equals 1000 processing units.
- PROCESSING_UNIT_COUNT: the compute capacity of the instance,expressed as a number of processing units. Enter quantities up to 1000in multiples of 100 (100, 200, 300 and so on) and enter greaterquantities in multiples of 1000 (1000, 2000, 3000 and so on).
Label an instance
Labels help organize your resources.
Console
Go to theSpanner Instances page in the Google Cloud console.
Select the checkbox for the instance. TheInfo panel appears on theright-hand side of the page.
Click theLabels tab in theInfo panel. You can then add, deleteor update labels for the Spanner instance.
Edit the default backup schedule type
Default backup schedules are automatically enabled for all new instances. Youcan enable or disable default backup schedules in an instance when creating theinstance or by editing the instance later. For more information, seeDefault backup schedules.
Console
Go to theSpanner Instances page in the Google Cloud console.
Click the name of the instance that you want to edit the defaultbackup schedule.
ClickEdit instance.
UnderBackups, theEnable default backup schedules checkbox determineswhether default backup schedules are enabled or not. When enabled, allnew databases in this instance have a default backup schedule created.
ClickSave.
gcloud
Use thegcloud spanner instances updatecommand to edit the default backup schedules type.
You can edit the default backup schedule type by running the following command:
gcloudspannerinstancesupdateINSTANCE_ID\--default-backup-schedule-type=DEFAULT_BACKUP_SCHEDULE_TYPE
Replace the following:
- INSTANCE_ID: the permanent identifier for the instance.
DEFAULT_BACKUP_SCHEDULE_TYPE: the default backup scheduletype that is used in the instance. Must be one of the following values:
AUTOMATIC: a default backup schedule is created automaticallywhen a new database is created in the instance. The default backupschedule creates a full backup every 24 hours. These full backupsare retained for 7 days. You can edit or delete the default backupschedule once it's created.NONE: a default backup schedule isn't created automatically when anew database is created in the instance.
C#
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
usingGoogle.Cloud.Spanner.Admin.Instance.V1;usingGoogle.Cloud.Spanner.Common.V1;usingGoogle.LongRunning;usingGoogle.Protobuf.WellKnownTypes;usingSystem;usingSystem.Threading.Tasks;publicclassUpdateInstanceDefaultBackupScheduleTypeAsyncSample{publicasyncTask<Instance>UpdateInstanceDefaultBackupScheduleTypeAsync(stringprojectId,stringinstanceId){// Create the InstanceAdminClient instance.InstanceAdminClientinstanceAdminClient=awaitInstanceAdminClient.CreateAsync();// Initialize request parameters.Instanceinstance=newInstance{InstanceName=InstanceName.FromProjectInstance(projectId,instanceId),DefaultBackupScheduleType=Instance.Types.DefaultBackupScheduleType.Automatic,};FieldMaskmask=newFieldMask{Paths={"default_backup_schedule_type"}};// Make the CreateInstance request.Operation<Instance,UpdateInstanceMetadata>response=awaitinstanceAdminClient.UpdateInstanceAsync(instance,mask);Console.WriteLine("Waiting for the operation to finish.");// Poll until the returned long-running operation is complete.Operation<Instance,UpdateInstanceMetadata>completedResponse=awaitresponse.PollUntilCompletedAsync();if(completedResponse.IsFaulted){Console.WriteLine($"Error while updating instance: {completedResponse.Exception}");throwcompletedResponse.Exception;}Console.WriteLine($"Instance updated successfully.");returncompletedResponse.Result;}}Go
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
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/genproto/protobuf/field_mask")// updateInstanceDefaultBackupScheduleType updates instance default backup schedule type to AUTOMATIC.// This means a default backup schedule will be created automatically on creation of a database within the instance.funcupdateInstanceDefaultBackupScheduleType(wio.Writer,projectID,instanceIDstring)error{// projectID := "my-project-id"// instanceID := "my-instance"ctx:=context.Background()instanceAdmin,err:=instance.NewInstanceAdminClient(ctx)iferr!=nil{returnerr}deferinstanceAdmin.Close()// Updates the default backup schedule type field of an instance. The field mask is required to// indicate which field is being updated.req:=&instancepb.UpdateInstanceRequest{Instance:&instancepb.Instance{Name:fmt.Sprintf("projects/%s/instances/%s",projectID,instanceID),// Controls the default backup behavior for new databases within the instance.DefaultBackupScheduleType:instancepb.Instance_AUTOMATIC,},FieldMask:&field_mask.FieldMask{Paths:[]string{"default_backup_schedule_type"},},}op,err:=instanceAdmin.UpdateInstance(ctx,req)iferr!=nil{returnfmt.Errorf("could not update instance %s: %w",fmt.Sprintf("projects/%s/instances/%s",projectID,instanceID),err)}// Wait for the instance update to finish._,err=op.Wait(ctx)iferr!=nil{returnfmt.Errorf("waiting for instance update to finish failed: %w",err)}fmt.Fprintf(w,"Updated instance [%s]\n",instanceID)returnnil}Java
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;importcom.google.common.collect.Lists;importcom.google.protobuf.FieldMask;importcom.google.spanner.admin.instance.v1.Instance;importcom.google.spanner.admin.instance.v1.InstanceConfigName;importcom.google.spanner.admin.instance.v1.InstanceName;importcom.google.spanner.admin.instance.v1.UpdateInstanceRequest;importjava.util.concurrent.ExecutionException;publicclassUpdateInstanceDefaultBackupScheduleTypeExample{staticvoidupdateInstanceDefaultBackupScheduleType(){// TODO(developer): Replace these variables before running the sample.StringprojectId="my-project";StringinstanceId="my-instance";updateInstanceDefaultBackupScheduleType(projectId,instanceId);}staticvoidupdateInstanceDefaultBackupScheduleType(StringprojectId,StringinstanceId){// Set Instance configuration.intnodeCount=2;StringdisplayName="Updated name";// Update an Instance object that will be used to update the instance.Instanceinstance=Instance.newBuilder().setName(InstanceName.of(projectId,instanceId).toString()).setDisplayName(displayName).setNodeCount(nodeCount).setDefaultBackupScheduleType(Instance.DefaultBackupScheduleType.AUTOMATIC).setConfig(InstanceConfigName.of(projectId,"regional-us-east4").toString()).build();try(Spannerspanner=SpannerOptions.newBuilder().setProjectId(projectId).build().getService();InstanceAdminClientinstanceAdminClient=spanner.createInstanceAdminClient()){// Wait for the updatedInstance operation to finish.InstanceupdatedInstance=instanceAdminClient.updateInstanceAsync(UpdateInstanceRequest.newBuilder().setFieldMask(FieldMask.newBuilder().addAllPaths(Lists.newArrayList("default_backup_schedule_type"))).setInstance(instance).build()).get();System.out.printf("Instance %s was successfully updated%n",updatedInstance.getName());}catch(ExecutionExceptione){System.out.printf("Error: Updating instance %s failed with error message %s%n",instance.getName(),e.getMessage());}catch(InterruptedExceptione){System.out.println("Error: Waiting for updateInstance operation to finish was interrupted");}}}Node.js
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
/** * TODO(developer): Uncomment the following lines before running the sample. */// const projectId = 'my-project-id';// const instanceId = 'my-instance';// Imports the Google Cloud client libraryconst{Spanner,protos}=require('@google-cloud/spanner');// Creates a clientconstspanner=newSpanner({projectId:projectId,});constinstanceAdminClient=awaitspanner.getInstanceAdminClient();// Updates an instancetry{const[operation]=awaitinstanceAdminClient.updateInstance({instance:{name:instanceAdminClient.instancePath(projectId,instanceId),defaultBackupScheduleType:protos.google.spanner.admin.instance.v1.Instance.DefaultBackupScheduleType.AUTOMATIC,// optional},// Field mask specifying fields that should get updated in an InstancefieldMask:(protos.google.protobuf.FieldMask={paths:['default_backup_schedule_type'],}),});awaitoperation.promise();const[metadata]=awaitinstanceAdminClient.getInstance({name:instanceAdminClient.instancePath(projectId,instanceId),});console.log(`Instance${instanceId} has been updated with the${metadata.defaultBackupScheduleType}`+' default backup schedule type.',);}catch(err){console.error('ERROR:',err);}Python
To learn how to install and use the client library for Spanner, seeSpanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
defupdate_instance_default_backup_schedule_type(instance_id):spanner_client=spanner.Client()name="{}/instances/{}".format(spanner_client.project_name,instance_id)operation=spanner_client.instance_admin_api.update_instance(instance=spanner_instance_admin.Instance(name=name,default_backup_schedule_type=spanner_instance_admin.Instance.DefaultBackupScheduleType.AUTOMATIC,# Optional),field_mask=field_mask_pb2.FieldMask(paths=["default_backup_schedule_type"]),)print("Waiting for operation to complete...")operation.result(OPERATION_TIMEOUT_SECONDS)print("Updated instance{} to have default backup schedules".format(instance_id))Move an instance
Note: You can't move an instance that has managed autoscaler enabled.For instructions on how to move your instance from any instance configuration toany other instance configuration, including between regional and multi-regionalconfigurations, seeMove an instance.
Delete an instance
Warning: Deleting an instance permanently removes the instance and all itsdatabases. You can't undo this later.Also, you can't create anotherfree trial instance once you've deleted your first free trial instance. Youcan create one free trial instance per project lifecycle.You can delete an instance with the Google Cloud console or theGoogle Cloud CLI.
If you want to delete an instance that has one or more databases withdeletion protection enabled, you must firstdisable the deletion protectionon all databases in that instance before you can delete the instance.
Console
Go to theSpanner Instances page in the Google Cloud console.
Click the name of the instance that you want to delete.
ClickDelete instance.
Follow the instructions to confirm that you want to delete the instance.
ClickDelete.
gcloud
Use thegcloud spanner instances deletecommand, replacingINSTANCE_ID with the instance ID:
gcloud spanner instances deleteINSTANCE_ID
Stop or restart an instance
Spanner is a fully managed database service which oversees itsown underlying tasks and resources, including monitoring and restartingprocesses when necessary with zero downtime. As there is no need to manuallystop or restart a given instance, Spanner does not offer a way todo so.
What's next
- Learn how to insert, update, and delete data withData Manipulation Language (DML) or thegcloud CLI.
- GrantIdentity and Access Management roles for the instance and its databases.
- Understand how todesign a Spanner schema.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.