List clusters

Lists the clusters in the instance.

Code sample

C#

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

To authenticate to Bigtable, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// Lists clusters in the instance.
// Initialize request argument(s)
ListClustersRequest listClustersRequest = new ListClustersRequest
{
    ParentAsInstanceName = new InstanceName(projectId, instanceId)
};

try
{
    // Make a request.
    Console.WriteLine("Waiting for operation to complete...");
    ListClustersResponse response = bigtableInstanceAdminClient.ListClusters(listClustersRequest);
}
catch (Exception ex)
{
    Console.WriteLine($"Exception while requesting information about clusters in {instanceId} instance");
    Console.WriteLine(ex.Message);
}

Go

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

To authenticate to Bigtable, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import (
	"context"
	"fmt"
	"io"

	bigtableadmin "cloud.google.com/go/bigtable/admin/apiv2"
	"cloud.google.com/go/bigtable/admin/apiv2/adminpb"
)

// listClusters lists the Cloud Bigtable clusters in an instance.
func listClusters(ctx context.Context, w io.Writer, projectID string, instanceID string) error {
	parent := fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID)

	client, err := bigtableadmin.NewBigtableInstanceAdminClient(ctx)
	if err != nil {
		return fmt.Errorf("NewBigtableInstanceAdminClient failed: %w", err)
	}
	defer client.Close()

	req := &adminpb.ListClustersRequest{
		Parent: parent,
	}

	resp, err := client.ListClusters(ctx, req)
	if err != nil {
		return fmt.Errorf("ListClusters: %w", err)
	}

	for _, cluster := range resp.GetClusters() {
		fmt.Fprintf(w, "Cluster: %s\n", cluster.GetName())
	}

	return nil
}

Java

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

To authenticate to Bigtable, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.google.bigtable.admin.v2.Cluster;
import com.google.bigtable.admin.v2.ListClustersRequest;
import com.google.bigtable.admin.v2.ListClustersResponse;
import com.google.cloud.bigtable.admin.v2.BigtableInstanceAdminClientV2;
import java.io.IOException;

public class ListClusters {

  /** Lists all clusters in the specified Cloud Bigtable instance. */
  public static void listClusters(String projectId, String instanceId) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // String projectId = "my-project-id";
    // String instanceId = "my-instance-id";

    try (BigtableInstanceAdminClientV2 adminClient = BigtableInstanceAdminClientV2.create()) {
      String parent = "projects/" + projectId + "/instances/" + instanceId;
      ListClustersRequest request = ListClustersRequest.newBuilder().setParent(parent).build();
      ListClustersResponse response = adminClient.listClusters(request);
      for (Cluster cluster : response.getClustersList()) {
        System.out.println(cluster.getName());
      }
    }
  }
}

Node.js

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

To authenticate to Bigtable, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

'use strict';

const {BigtableInstanceAdminClient} = require('@google-cloud/bigtable').v2;
const {status} = require('@grpc/grpc-js');

const client = new BigtableInstanceAdminClient();

/**
 * Lists Bigtable clusters in a specified instance or across all instances in a project.
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id').
 * @param {string} instanceId - The ID of the Bigtable instance (for example, 'example-instance-id'), or '-' to list clusters across all instances in the project.
 */
async function listClusters(projectId, instanceId) {
  try {
    const parent = `projects/${projectId}/instances/${instanceId}`;

    const request = {
      parent,
    };

    const [response] = await client.listClusters(request);
    const clusters = response.clusters || [];

    console.log(`Clusters in ${parent}:`);
    for (const cluster of clusters) {
      console.log(`- Name: ${cluster.name}`);
      console.log(`  Location: ${cluster.location}`);
      console.log(`  Serve nodes: ${cluster.serveNodes}`);
      console.log(`  Default storage type: ${cluster.defaultStorageType}`);
    }

    return clusters;
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Resource not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument: ${err.message}`);
    } else {
      console.error(`API error (${err.code}): ${err.message}`);
    }
    throw err;
  }
}

module.exports = { listClusters };

Python

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

To authenticate to Bigtable, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import google.api_core.exceptions
from google.cloud import bigtable_admin_v2


def list_clusters(project_id: str, instance_id: str) -> None:
    """Lists clusters for a Cloud Bigtable instance.

    Args:
        project_id: The Google Cloud project ID (for example, 'example-project-id').
        instance_id: The ID of the Bigtable instance to list clusters for, or '-'
          to list clusters across all instances (for example, 'example-instance' or '-').
    """
    client = bigtable_admin_v2.BigtableInstanceAdminClient()
    parent = f"projects/{project_id}/instances/{instance_id}"

    try:
        response = client.list_clusters(parent=parent)
        for cluster in response.clusters:
            print(f"Cluster: {cluster.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"API call failed: {error}")

What's next

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