列出项目中的映像

此示例演示了如何列出给定项目中所有可用的映像。

代码示例

Java

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

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


import com.google.cloud.compute.v1.Image;
import com.google.cloud.compute.v1.ImagesClient;
import com.google.cloud.compute.v1.ListImagesRequest;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ListImages {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";

    listImages(projectId);
  }

  // Retrieve a list of images available in given project.
  public static List<Image> listImages(String projectId) 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.
    try (ImagesClient client = ImagesClient.create()) {
      ListImagesRequest request = ListImagesRequest.newBuilder()
              .setProject(projectId)
              .build();

      ArrayList<Image> images = Lists.newArrayList(client.list(request).iterateAll());

      System.out.printf("'%s' images has been retrieved successfully", images.size());

      return images;
    }
  }
}

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_images(project_id: str) -> Iterable[compute_v1.Image]:
    """
    Retrieve a list of images available in given project.

    Args:
        project_id: project ID or project number of the Cloud project you want to list images from.

    Returns:
        An iterable collection of compute_v1.Image objects.
    """
    image_client = compute_v1.ImagesClient()
    return image_client.list(project=project_id)

后续步骤

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