指定したファミリーから最新のイメージを取得する

このサンプルでは、プロジェクト内の特定のファミリーに属する最新のイメージを取得します。

コードサンプル

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"
)

// Geg a disk image from family for the given project
func getDiskImageFromFamily(
	w io.Writer,
	projectID, family string,
) (*computepb.Image, error) {
	// projectID := "your_project_id"
	// family := "my_family"

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

	source_req := &computepb.GetFromFamilyImageRequest{
		Project: projectID,
		Family:  family,
	}

	newestImage, err := imagesClient.GetFromFamily(ctx, source_req)
	if err != nil {
		return nil, fmt.Errorf("unable to get image: %w", err)
	}

	fmt.Fprintf(w, "Newest disk image was found: %s\n", *newestImage.Name)

	return newestImage, nil
}

Java

このサンプルを試す前に、Compute Engine クイックスタート: クライアント ライブラリの使用に記載されている Java の設定手順に沿って操作します。 詳細については、Compute Engine Java API リファレンス ドキュメントをご覧ください。

Compute Engine に対して認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


import com.google.cloud.compute.v1.GetFromFamilyImageRequest;
import com.google.cloud.compute.v1.Image;
import com.google.cloud.compute.v1.ImagesClient;
import java.io.IOException;

public class GetImageFromFamily {
  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 = "debian-cloud";
    // Name of the image family you want to retrieve the image from.
    // List of public operating system (OS) images:
    // https://cloud.google.com/compute/docs/images/os-details
    String family = "debian-11";

    getImageFromFamily(projectId, family);
  }

  // Retrieve the newest image that is part of a given family in a project.
  public static Image getImageFromFamily(String projectId, String family) 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()) {
      GetFromFamilyImageRequest request = GetFromFamilyImageRequest.newBuilder()
              .setProject(projectId)
              .setFamily(family)
              .build();

      Image image = client.getFromFamily(request);

      System.out.printf("Image '%s' has been retrieved successfully", image.getName());

      return image;
    }
  }
}

Python

このサンプルを試す前に、Compute Engine クイックスタート: クライアント ライブラリの使用に記載されている Python の設定手順に沿って操作します。 詳細については、Compute Engine Python API リファレンス ドキュメントをご覧ください。

Compute Engine に対して認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import compute_v1



def get_image_from_family(project: str, family: str) -> compute_v1.Image:
    """
    Retrieve the newest image that is part of a given family in a project.

    Args:
        project: project ID or project number of the Cloud project you want to get image from.
        family: name of the image family you want to get image from.

    Returns:
        An Image object.
    """
    image_client = compute_v1.ImagesClient()
    # List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
    newest_image = image_client.get_from_family(project=project, family=family)
    return newest_image

次のステップ

他の Google Cloud プロダクトに関連するコードサンプルを検索およびフィルタするには、Google Cloud のサンプル ブラウザをご覧ください。