列出可用区中的磁盘

此示例会列出给定可用区中的所有磁盘。

代码示例

Go

试用此示例之前,请按照《Compute Engine 快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Compute Engine Go API 参考文档

如需向 Compute Engine 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

试用此示例之前,请按照《Compute Engine 快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Compute Engine Java API 参考文档

如需向 Compute Engine 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

试用此示例之前,请按照《Compute Engine 快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Compute Engine Python API 参考文档

如需向 Compute Engine 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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)

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器