List disks in a zone

This sample lists all the disks in a given zone.

Code sample

Go

Before trying this sample, follow the Go setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Go API reference documentation.

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

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
)

// listDisks lists disks in a project zone.
func listDisks(w io.Writer, projectID, zone, filter string) error {
	// projectID := "your_project_id"
	// zone := "us-central1-a"
	// filter := ""

	// Formatting for filters:
	// https://cloud.google.com/python/docs/reference/compute/latest/google.cloud.compute_v1.types.ListDisksRequest

	ctx := context.Background()
	client, err := compute.NewDisksRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewDisksRESTClient: %w", err)
	}
	defer client.Close()

	req := &computepb.ListDisksRequest{
		Project: projectID,
		Zone:    zone,
		Filter:  &filter,
	}

	it := client.List(ctx, req)
	fmt.Fprintf(w, "Disks in zone %s:\n", zone)
	for {
		disk, err := it.Next()
		if err == context.Canceled || err == context.DeadlineExceeded {
			return err
		}
		if err != nil {
			break
		}
		fmt.Fprintf(w, "- %s\n", *disk.Name)
	}

	if err != nil {
		return fmt.Errorf("ListDisks: %w", err)
	}
	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Java API reference documentation.

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


import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.ListDisksRequest;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class ListDisks {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.

    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // The zone where the disks are located.
    String zone = "europe-central2-b";

    // Filter to be applied when listing disks. Learn more about filters here:
    // https://cloud.google.com/python/docs/reference/compute/latest/google.cloud.compute_v1.types.ListDisksRequest
    String filter = "FILTER_CONDITION";

    listDisks(projectId, zone, filter);
  }

  // Lists disks from a project.
  public static void listDisks(String projectId, String zone, String filter)
      throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `disksClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (DisksClient disksClient = DisksClient.create()) {

      // Create the request object.
      ListDisksRequest listDisksRequest = ListDisksRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setFilter(filter)
          .build();

      System.out.println("List of disks:");
      for (Disk disk : disksClient.list(listDisksRequest).iterateAll()) {
        System.out.println(disk.getName());
      }
    }
  }
}

Python

Before trying this sample, follow the Python setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Python API reference documentation.

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

from __future__ import annotations

from collections.abc import Iterable

from google.cloud import compute_v1


def list_disks(
    project_id: str, zone: str, filter_: str = ""
) -> Iterable[compute_v1.Disk]:
    """
    Lists disks in a project.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone
        filter_: filter to be applied when listing disks. Learn more about filters here:
            https://cloud.google.com/python/docs/reference/compute/latest/google.cloud.compute_v1.types.ListDisksRequest
    """
    disk_client = compute_v1.DisksClient()
    request = compute_v1.ListDisksRequest()
    request.project = project_id
    request.zone = zone
    request.filter = filter_
    return disk_client.list(request)

What's next

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