淘汰自訂映像檔


Compute Engine 可讓您在映像檔上設定淘汰狀態,以淘汰您擁有的自訂映像檔。每一種淘汰狀態會引起不同的伺服器反應,協助您採用易管理的方法,為使用者淘汰不再支援的映像檔。您可以使用 Google Cloud 控制台、Google Cloud CLI 或 Compute Engine API 方法來淘汰映像檔。

淘汰狀態

支援的淘汰狀態如下:

  • ACTIVE:圖片有效,可正常使用。映像檔系列會指向系列中最新且有效的映像檔。
  • DEPRECATED:映像檔標示為已淘汰,但仍可用於建立 VM。 您仍然可以建立此圖片的新連結。即使它是系列中最新的映像檔,映像檔系列也不再指向此映像檔。

    如果您使用 Google Cloud CLI 透過已淘汰的映像檔建立 VM,要求會成功執行,但會顯示警告。

  • OBSOLETE:圖片已標示為過時,無法再使用。 如果您嘗試在要求中使用此映像檔,系統會傳回錯誤訊息。仍然允許對於此映像檔的現有連結。

  • DELETED:這張圖片已刪除。如果您嘗試使用已刪除的圖片,系統會傳回錯誤訊息。

如要還原淘汰狀態 (再次啟用圖片),請將淘汰狀態變更為 ACTIVE

事前準備

  • 參閱映像檔文件。
  • 如果尚未設定驗證,請先完成設定。 「驗證」是指驗證身分的程序,確認您有權存取 Google Cloud 服務和 API。如要從本機開發環境執行程式碼或範例,請選取下列其中一個選項,向 Compute Engine 進行驗證:

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

      1. After installing the Google Cloud CLI, initialize it by running the following command:

        gcloud init

        If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      2. Set a default region and zone.
      3. REST

        如要在本機開發環境中使用本頁的 REST API 範例,請使用您提供給 gcloud CLI 的憑證。

          After installing the Google Cloud CLI, initialize it by running the following command:

          gcloud init

          If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

        詳情請參閱 Google Cloud 驗證說明文件中的「Authenticate for using REST」。

淘汰自訂映像檔

主控台

  1. 前往 Google Cloud 控制台的「Images」(映像檔) 頁面。

    前往「圖片」

  2. 找出要淘汰的映像檔,然後按一下「動作」

  3. 選取「淘汰」

  4. 選取「已淘汰」或「已過時」。 如要進一步瞭解狀態,請參閱「淘汰狀態」。

  5. 選用:指定替代圖片。

  6. 按一下「淘汰映像檔」

gcloud

使用 gcloud compute images deprecate 指令設定映像檔的淘汰狀態。

gcloud compute images deprecate IMAGE_NAME \
    --state STATE \
    --replacement REPLACEMENT

更改下列內容:

  • IMAGE_NAME:要淘汰的映像檔名稱
  • STATE廢止狀態
  • REPLACEMENT:要用來取代淘汰映像檔的映像檔

Go

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/protobuf/proto"
)

// Geg a disk image from the given project
func deprecateDiskImage(
	w io.Writer,
	projectID, imageName string,
) error {
	// projectID := "your_project_id"
	// imageName := "my_image"

	deprecationStatus := &computepb.DeprecationStatus{
		State: proto.String(computepb.DeprecationStatus_DEPRECATED.String()),
	}

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

	source_req := &computepb.DeprecateImageRequest{
		Project:                   projectID,
		Image:                     imageName,
		DeprecationStatusResource: deprecationStatus,
	}

	op, err := imagesClient.Deprecate(ctx, source_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 deprecated\n", imageName)

	return nil
}

Java


import com.google.cloud.compute.v1.DeprecateImageRequest;
import com.google.cloud.compute.v1.DeprecationStatus;
import com.google.cloud.compute.v1.Image;
import com.google.cloud.compute.v1.ImagesClient;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class SetImageDeprecationStatus {
  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 update.
    String imageName = "your-image-name";
    // The status you want to set for the image. Available values are available in
    // `compute_v1.DeprecationStatus.State` enum. Learn more about image deprecation statuses:
    // https://cloud.google.com/compute/docs/images/create-delete-deprecate-private-images#deprecation-states
    DeprecationStatus.State status = DeprecationStatus.State.DEPRECATED;

    setDeprecationStatus(projectId, imageName, status);
  }

  // Modify the deprecation status of an image.
  public static Image setDeprecationStatus(String projectId, String imageName,
                                           DeprecationStatus.State status)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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()) {
      DeprecationStatus deprecationStatusResource = DeprecationStatus.newBuilder()
              .setState(status.name())
              .build();
      DeprecateImageRequest request = DeprecateImageRequest.newBuilder()
              .setProject(projectId)
              .setImage(imageName)
              .setDeprecationStatusResource(deprecationStatusResource)
              .setRequestId(UUID.randomUUID().toString())
              .build();

      client.deprecateCallable().futureCall(request).get(60, TimeUnit.SECONDS);

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

      System.out.printf("Status '%s' has been updated successfully",
              image.getDeprecated().getState());

      return image;
    }
  }
}

Python

from __future__ import annotations

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 set_deprecation_status(
    project_id: str, image_name: str, status: compute_v1.DeprecationStatus.State
) -> None:
    """
    Modify the deprecation status of an image.

    Note: Image objects by default don't have the `deprecated` attribute at all unless it's set.

    Args:
        project_id: project ID or project number of the Cloud project that hosts the image.
        image_name: name of the image you want to modify
        status: the status you want to set for the image. Available values are available in
            `compute_v1.DeprecationStatus.State` enum. Learn more about image deprecation statuses:
            https://cloud.google.com/compute/docs/images/create-delete-deprecate-private-images#deprecation-states
    """
    image_client = compute_v1.ImagesClient()
    deprecation_status = compute_v1.DeprecationStatus()
    deprecation_status.state = status.name
    operation = image_client.deprecate(
        project=project_id,
        image=image_name,
        deprecation_status_resource=deprecation_status,
    )

    wait_for_extended_operation(operation, "changing deprecation state of an image")

REST

images().deprecate 方法發出 POST 要求。指定要淘汰的映像檔名稱。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/images/RESOURCE_ID/deprecate

{
  "state": "STATE",
  "replacement": "REPLACEMENT"
}

更改下列內容:

  • PROJECT_ID:映像檔所屬的專案。
  • RESOURCE_ID:要淘汰的映像檔名稱。
  • STATE:這項資源的淘汰狀態
  • REPLACEMENT:要用來取代淘汰映像檔的映像檔。