Ein Image von einem anderen Image erstellen

In diesem Beispiel wird eine Kopie eines anderen Images erstellt.

Codebeispiel

Python

Bevor Sie dieses Beispiel anwenden, folgen Sie den Schritten zur Einrichtung von Python in der Compute Engine-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Compute Engine Python API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Compute Engine zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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)

Nächste Schritte

Informationen zum Suchen und Filtern von Codebeispielen für andere Google Cloud-Produkte finden Sie im Google Cloud-Beispielbrowser.