弃用自定义映像


Compute Engine 可让您在映像上设置弃用状态,以便弃用您所拥有的自定义映像。每个弃用状态都会引起服务器的不同响应,从而帮助您以一种可管理的方式将用户从不受支持的映像转移出去。可以使用 Google Cloud 控制台、Google Cloud CLI 或 Compute Engine API 方法来弃用映像。

弃用状态

支持以下弃用状态:

  • ACTIVE:映像处于活跃状态,并且可以正常使用。映像系列指向一个系列中最新、最活跃的映像。
  • DEPRECATED:映像被标记为“已弃用”,但仍可用于创建虚拟机。您可以为此映像创建新的链接。即使此映像是某个系列中最新的映像,映像系列也不会再指向此映像。

    如果您使用 Google Cloud CLI 创建具有已弃用映像的虚拟机,则请求会成功并显示一条警告。

  • 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. Install the Google Cloud CLI, then initialize it by running the following command:

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

      如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 gcloud CLI 的凭据。

        Install the Google Cloud CLI, then initialize it by running the following command:

        gcloud init

      如需了解详情,请参阅 Google Cloud 身份验证文档中的使用 REST 时进行身份验证

弃用自定义映像

控制台

  1. 在 Google Cloud 控制台中,转到映像页面。

    转到“映像”

  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:用于替换弃用映像的映像。