Create instance

Stay organized with collections Save and categorize content based on your preferences.

Create an instance.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample


To learn how to install and use the client library for Spanner, see Spanner client libraries.

using Google.Api.Gax.ResourceNames;
using Google.Cloud.Spanner.Admin.Instance.V1;
using Google.Cloud.Spanner.Common.V1;
using Google.LongRunning;
using System;

public class CreateInstanceSample
    public Instance CreateInstance(string projectId, string instanceId)
        // Create the InstanceAdminClient instance.
        InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create();

        // Initialize request parameters.
        Instance instance = new Instance
            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" },
        ProjectName projectName = ProjectName.FromProject(projectId);

        // Make the CreateInstance request.
        Operation<Instance, CreateInstanceMetadata> response = instanceAdminClient.CreateInstance(projectName, instanceId, instance);

        Console.WriteLine("Waiting for the operation to finish.");

        // Poll until the returned long-running operation is complete.
        Operation<Instance, CreateInstanceMetadata> completedResponse = response.PollUntilCompleted();

        if (completedResponse.IsFaulted)
            Console.WriteLine($"Error while creating instance: {completedResponse.Exception}");
            throw completedResponse.Exception;

        Console.WriteLine($"Instance created successfully.");

        return completedResponse.Result;


To learn how to install and use the client library for Spanner, see Spanner client libraries.

void CreateInstance(google::cloud::spanner_admin::InstanceAdminClient client,
                    std::string const& project_id,
                    std::string const& instance_id,
                    std::string const& display_name,
                    std::string const& config_id) {
  namespace spanner = ::google::cloud::spanner;
  spanner::Instance in(project_id, instance_id);

  auto project = google::cloud::Project(project_id);
  std::string config_name =
      project.FullName() + "/instanceConfigs/" + config_id;
  auto instance =
          .CreateInstance(spanner::CreateInstanceRequestBuilder(in, config_name)
                              .SetLabels({{"cloud_spanner_samples", "true"}})
  if (!instance) throw std::move(instance).status();
  std::cout << "Created instance [" << in << "]:\n" << instance->DebugString();


To learn how to install and use the client library for Spanner, see Spanner client libraries.

import (

	instance ""
	instancepb ""

func createInstance(w io.Writer, projectID, instanceID string) error {
	// projectID := "my-project-id"
	// instanceID := "my-instance"
	ctx := context.Background()
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	defer instanceAdmin.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"},
	if err != nil {
		return fmt.Errorf("could not create instance %s: %v", fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID), err)
	// Wait for the instance creation to finish.
	i, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("waiting for instance creation to finish failed: %v", err)
	// The instance may not be ready to serve yet.
	if i.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)
	return nil


To learn how to install and use the client library for Spanner, see Spanner client libraries.

import java.util.concurrent.ExecutionException;

class CreateInstanceExample {

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

  static void createInstance(String projectId, String instanceId) {
    Spanner spanner = SpannerOptions.newBuilder().setProjectId(projectId).build().getService();
    InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient();

    // Set Instance configuration.
    String configId = "regional-us-central1";
    int nodeCount = 2;
    String displayName = "Descriptive name";

    // Create an InstanceInfo object that will be used to create the instance.
    InstanceInfo instanceInfo =
        InstanceInfo.newBuilder(InstanceId.of(projectId, instanceId))
            .setInstanceConfigId(InstanceConfigId.of(projectId, configId))
    OperationFuture<Instance, CreateInstanceMetadata> operation =
    try {
      // Wait for the createInstance operation to finish.
      Instance instance = operation.get();
      System.out.printf("Instance %s was successfully created%n", instance.getId());
    } catch (ExecutionException e) {
          "Error: Creating instance %s failed with error message %s%n",
          instanceInfo.getId(), e.getMessage());
    } catch (InterruptedException e) {
      System.out.println("Error: Waiting for createInstance operation to finish was interrupted");
    } finally {


To learn how to install and use the client library for Spanner, see Spanner client libraries.

// Imports the Google Cloud client library
const {Spanner} = 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 client
const spanner = new Spanner({
  projectId: projectId,

const instance = spanner.instance(instanceId);

// Creates a new instance
try {
  console.log(`Creating instance ${instance.formattedName_}.`);
  const [, operation] = await instance.create({
    config: 'regional-us-west1',
    nodes: 1,
    displayName: 'This is a display name.',
    labels: {
      ['cloud_spanner_samples']: 'true',
      created: Math.round( / 1000).toString(), // current time

  console.log(`Waiting for operation on ${} to complete...`);
  await operation.promise();

  console.log(`Created instance ${instanceId}.`);
} catch (err) {
  console.error('ERROR:', err);


To learn how to install and use the client library for Spanner, see Spanner client libraries.

use Google\Cloud\Spanner\SpannerClient;

 * Creates an instance.
 * Example:
 * ```
 * create_instance($instanceId);
 * ```
 * @param string $instanceId The Spanner instance ID.
function create_instance($instanceId)
    $spanner = new SpannerClient();
    $instanceConfig = $spanner->instanceConfiguration(
    $operation = $spanner->createInstance(
            'displayName' => 'This is a display name.',
            'nodeCount' => 1,
            'labels' => [
                'cloud_spanner_samples' => true,

    print('Waiting for operation to complete...' . PHP_EOL);

    printf('Created instance %s' . PHP_EOL, $instanceId);


To learn how to install and use the client library for Spanner, see Spanner client libraries.

def create_instance(instance_id):
    """Creates an instance."""
    spanner_client = spanner.Client()

    config_name = "{}/instanceConfigs/regional-us-central1".format(

    instance = spanner_client.instance(
        display_name="This is a display name.",
            "cloud_spanner_samples": "true",
            "sample_name": "snippets-create_instance-explicit",
            "created": str(int(time.time())),

    operation = instance.create()

    print("Waiting for operation to complete...")

    print("Created instance {}".format(instance_id))


To learn how to install and use the client library for Spanner, see Spanner client libraries.

# project_id  = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance 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
instance_path = instance_admin_client.instance_path project: project_id, instance: instance_id
instance_config_path = instance_admin_client.instance_config_path project: project_id, instance_config: "regional-us-central1"

job = instance_admin_client.create_instance parent: 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"


if job.error?
  puts job.error
  puts "Created instance #{instance_id}"

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.