다른 이미지에서 이미지 만들기

이 샘플은 다른 이미지의 사본을 만듭니다.

코드 샘플

Python

이 샘플을 사용해 보기 전에 Compute Engine 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Compute Engine Python API 참조 문서를 확인하세요.

Compute Engine에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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)

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.