Créer une image à partir d'une autre image

Cet exemple crée une copie d'une autre image.

Exemple de code

Go

Avant d'essayer cet exemple, suivez les instructions de configuration pour Go décrites dans le Guide de démarrage rapide de Compute Engine à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Go Compute Engine.

Pour vous authentifier auprès de Compute Engine, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
)

// Creates a disk image from an existing image
func createImageFromImage(
	w io.Writer,
	projectID, sourceProjectId, sourceImageName, imageName string,
) error {
	// projectID := "your_project_id"
	// sourceProjectId := "your_project_id"
	// sourceImageName := "your_image_name"
	// imageName := "my_image"

	// If storageLocations empty, automatically selects the closest one to the source
	storageLocations := []string{}
	ctx := context.Background()
	imagesClient, err := compute.NewImagesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewImagesRESTClient: %w", err)
	}
	defer imagesClient.Close()

	// Get the source image
	source_req := &computepb.GetImageRequest{
		Image:   sourceImageName,
		Project: sourceProjectId,
	}

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

	// Create the image
	req := computepb.InsertImageRequest{
		ImageResource: &computepb.Image{
			Name:             &imageName,
			SourceImage:      image.SelfLink,
			StorageLocations: storageLocations,
		},
		Project: projectID,
	}

	op, err := imagesClient.Insert(ctx, &req)

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Disk image %s created\n", imageName)

	return nil
}

Java

Avant d'essayer cet exemple, suivez les instructions de configuration pour Java décrites dans le Guide de démarrage rapide de Compute Engine à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Java Compute Engine.

Pour vous authentifier auprès de Compute Engine, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


import com.google.cloud.compute.v1.GuestOsFeature;
import com.google.cloud.compute.v1.Image;
import com.google.cloud.compute.v1.ImagesClient;
import com.google.cloud.compute.v1.InsertImageRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateImageFromImage {
  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 Google Cloud project you want to use.
    String projectId = "your-project-id";
    // Name of the image you want to copy.
    String sourceImageName = "your-image-name";
    // Name of the image you want to create.
    String imageName = "your-image-name";
    // Name of the project that hosts the source image. If left unset, it's assumed to equal
    // the `projectId`.
    String sourceProjectId = "your-source-project-id";
    // An iterable collection of guest features you want to enable for the bootable image.
    // Learn more about Guest OS features here:
    // https://cloud.google.com/compute/docs/images/create-delete-deprecate-private-images#guest-os-features
    List<String> guestOsFeature = new ArrayList<>();
    // The storage location of your image. For example, specify "us" to store the image in the
    // `us` multi-region, or "us-central1" to store it in the `us-central1` region.
    // If you do not make a selection,
    // Compute Engine stores the image in the multi-region closest to your image's source location.
    String storageLocation = "your-storage-location";

    createImageFromImage(projectId, sourceImageName, imageName,
            sourceProjectId, guestOsFeature, storageLocation);
  }

  // Creates a new disk image from an existing image.
  public static Image createImageFromImage(String projectId, String sourceImageName,
                                           String imageName, String sourceProjectId,
                                           List<String> guestOsFeatures, String storageLocation)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    if (sourceProjectId == null) {
      sourceProjectId = projectId;
    }

    // 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()) {
      Image sourceImage = client.get(sourceProjectId, sourceImageName);
      Image.Builder imageResource = Image.newBuilder()
              .setName(imageName)
              .setSourceImage(sourceImage.getSelfLink());

      if (storageLocation != null) {
        imageResource.addStorageLocations(storageLocation);
      }
      if (guestOsFeatures != null) {
        for (String feature : guestOsFeatures) {
          GuestOsFeature.Builder guestOsFeatureBuilder = GuestOsFeature.newBuilder()
                  .setType(feature);

          imageResource.addGuestOsFeatures(guestOsFeatureBuilder);
        }
      }

      InsertImageRequest request = InsertImageRequest.newBuilder()
              .setProject(projectId)
              .setRequestId(UUID.randomUUID().toString())
              .setImageResource(imageResource)
              .build();
      client.insertCallable().futureCall(request).get(60, TimeUnit.SECONDS);

      Image image = client.get(projectId, imageName);

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

      return image;
    }
  }
}

Python

Avant d'essayer cet exemple, suivez les instructions de configuration pour Python décrites dans le Guide de démarrage rapide de Compute Engine à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Python Compute Engine.

Pour vous authentifier auprès de Compute Engine, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

from __future__ import annotations

from collections.abc import Iterable
import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def create_image_from_image(
    project_id: str,
    source_image_name: str,
    image_name: str,
    source_project_id: str | None = None,
    guest_os_features: Iterable[str] | None = None,
    storage_location: str | None = None,
) -> compute_v1.Image:
    """
    Creates a copy of another image.

    Args:
        project_id: project ID or project number of the Cloud project you want to place your new image in.
        source_image_name: name of the image you want to copy.
        image_name: name of the image you want to create.
        source_project_id: name of the project that hosts the source image. If left unset, it's assumed to equal
            the `project_id`.
        guest_os_features: an iterable collection of guest features you want to enable for the bootable image.
            Learn more about Guest OS features here:
            https://cloud.google.com/compute/docs/images/create-delete-deprecate-private-images#guest-os-features
        storage_location: the storage location of your image. For example, specify "us" to store the image in the
            `us` multi-region, or "us-central1" to store it in the `us-central1` region. If you do not make a selection,
             Compute Engine stores the image in the multi-region closest to your image's source location.

    Returns:
        An Image object.
    """
    if source_project_id is None:
        source_project_id = project_id

    image_client = compute_v1.ImagesClient()
    src_image = image_client.get(project=source_project_id, image=source_image_name)

    image = compute_v1.Image()
    image.name = image_name
    image.source_image = src_image.self_link
    if storage_location:
        image.storage_locations = [storage_location]

    if guest_os_features:
        image.guest_os_features = [
            compute_v1.GuestOsFeature(type_=feature) for feature in guest_os_features
        ]

    operation = image_client.insert(project=project_id, image_resource=image)

    wait_for_extended_operation(operation, "image creation from image")

    return image_client.get(project=project_id, image=image_name)

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'explorateur d'exemples Google Cloud.