プロジェクト内のイメージを一覧取得する

このサンプルは、特定のプロジェクトで使用可能なすべてのイメージを一覧取得する方法を示します。

コードサンプル

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 のサンプル ブラウザをご覧ください。