רשימת דיסקים באזור

בדוגמה הזו מפורטים כל הדיסקים באזור נתון.

דוגמת קוד

Go

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Goההוראות להגדרה שבמדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Go API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaההוראות להגדרה שבמדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Java API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonההוראות להגדרה שבמדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Python API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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 .