刪除預留項目

本文說明如何永久刪除預留項目,無論是您建立的預留項目,還是 Compute Engine 為滿足未來預留項目要求而自動建立的預留項目。如要瞭解如何刪除未來預留項目,請改為參閱下列任一主題:

刪除預留項目,即可停止為不再需要的預留資源付費。或者,您也可以刪除預留項目,並以指定不同運算執行個體屬性 (例如不同機器類型) 的新預留項目取代。

限制

刪除預留項目之前,請考量下列事項:

  • 您只能從建立共用預留項目的專案中刪除共用預留項目。

  • 只有在沒有 Compute Engine 執行個體耗用明確指定的預留項目時,才能刪除該預留項目。如果有任何執行個體使用預留項目,請先執行下列任一操作,再刪除預留項目:

    • 刪除執行個體

    • 停止或暫停執行個體

  • 未來預留項目的自動建立預留項目,只能在預留期間結束後刪除。

  • 如果預留項目已附加至承諾使用合約,且合約指定了任何需要附加預留項目的資源類型,您就無法手動刪除預留項目。不過,您可以將現有附加預留項目替換為新的預留項目。

事前準備

  • 如果尚未設定驗證,請先完成設定。驗證機制會確認您的身分,以便授予 Google Cloud 服務和 API 的存取權。如要從本機開發環境執行程式碼或範例,您可以選取下列其中一個選項,向 Compute Engine 進行驗證:

    請根據您打算如何使用本頁範例,選取對應的分頁標籤:

    控制台

    使用 Google Cloud 控制台存取 Google Cloud 服務和 API 時,不需要設定驗證機制。

    gcloud

    1. 安裝 Google Cloud CLI,然後 使用聯合身分登入 gcloud CLI。 登入後,執行下列指令來初始化 Google Cloud CLI:

      gcloud init
  • 設定預設區域和可用區。
  • Go

    如要在本機開發環境中使用本頁面的 Go 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「 使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已 使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Java

    如要在本機開發環境中使用本頁的 Java 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「 使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已 使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Node.js

    如要在本機開發環境中使用本頁的 Node.js 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「 使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已 使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Python

    如要在本機開發環境中使用本頁的 Python 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「 使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已 使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    REST

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

      安裝 Google Cloud CLI,然後 使用聯合身分登入 gcloud CLI。

    詳情請參閱 Google Cloud 驗證說明文件中的「使用 REST 進行驗證」一節。

必要的角色

如要取得刪除預留項目所需的權限,請要求管理員授予您專案的 Compute 管理員 (roles/compute.admin) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

這個預先定義的角色具備 compute.reservations.delete 權限,可刪除預留項目。

您或許還可透過自訂角色或其他預先定義的角色取得這項權限。

刪除預留項目

如果刪除可由任何相符運算執行個體自動使用的預留項目,則使用已刪除預留項目的任何執行個體都會繼續運作。這些執行個體會繼續產生費用。

您可以刪除單一預留項目,也可以一次刪除多個預留項目。如要建立多個預留項目,請使用 Google Cloud 控制台。如果是單一預留項目,請選取下列任一選項:

控制台

  1. 前往 Google Cloud 控制台的「Reservations」(預留項目) 頁面。

    前往「Reservations」(預留項目) 頁面

  2. 在「On-demand reservations」(隨需預留項目) 分頁,選取要刪除的預留項目。

  3. 按一下「刪除」圖示 。

  4. 按一下「Delete」(刪除) 確認操作。

gcloud

如要刪除預留項目,請使用 gcloud compute reservations delete 指令:

gcloud compute reservations delete RESERVATION_NAME \
    --zone=ZONE

更改下列內容:

  • RESERVATION_NAME:預留項目名稱。

  • ZONE:預留項目所在的可用區。

Go

import (
	"context"
	"fmt"
	"io"

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

// Deletes the reservation for given project and zone
func deleteReservation(w io.Writer, projectID, zone, reservationName string) error {
	// projectID := "your_project_id"
	// zone := "us-west3-a"
	// reservationName := "your_reservation_name"

	ctx := context.Background()
	reservationsClient, err := compute.NewReservationsRESTClient(ctx)
	if err != nil {
		return err
	}
	defer reservationsClient.Close()

	req := &computepb.DeleteReservationRequest{
		Project:     projectID,
		Reservation: reservationName,
		Zone:        zone,
	}

	op, err := reservationsClient.Delete(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to delete reservation: %w", err)
	}

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

	fmt.Fprintf(w, "Reservation deleted\n")

	return nil
}

Java

import com.google.cloud.compute.v1.DeleteReservationRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.ReservationsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteReservation {

  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 Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the reservation you want to delete.
    String reservationName = "YOUR_RESERVATION_NAME";
    // Name of the zone.
    String zone = "us-central1-a";

    deleteReservation(projectId, zone, reservationName);
  }

  // Delete a reservation from the project.
  public static void deleteReservation(String projectId, String zone, String reservationName)
      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 (ReservationsClient reservationsClient = ReservationsClient.create()) {

      DeleteReservationRequest deleteReservationRequest = DeleteReservationRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setReservation(reservationName)
          .build();

      Operation response = reservationsClient.deleteAsync(
          deleteReservationRequest).get(5, TimeUnit.MINUTES);

      if (response.getStatus() == Operation.Status.DONE) {
        System.out.println("Deleted reservation: " + reservationName);
      }
    }
  }
}

Node.js

// Import the Compute library
const computeLib = require('@google-cloud/compute');
// Instantiate a reservationsClient
const reservationsClient = new computeLib.ReservationsClient();
// Instantiate a zoneOperationsClient
const zoneOperationsClient = new computeLib.ZoneOperationsClient();
/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The ID of the project where your reservation is located.
const projectId = await reservationsClient.getProjectId();
// The zone where your reservation is located.
const zone = 'us-central1-a';
// The name of the reservation to delete.
// reservationName = 'reservation-01';

async function callDeleteReservation() {
  // Delete the reservation
  const [response] = await reservationsClient.delete({
    project: projectId,
    reservation: reservationName,
    zone,
  });

  let operation = response.latestResponse;

  // Wait for the delete reservation operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await zoneOperationsClient.wait({
      operation: operation.name,
      project: projectId,
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log(`Reservation: ${reservationName} deleted.`);
}
await callDeleteReservation();

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 delete_compute_reservation(
    project_id: str,
    zone: str = "us-central1-a",
    reservation_name="your-reservation-name",
) -> ExtendedOperation:
    """
    Deletes a compute reservation in Google Cloud.
    Args:
        project_id (str): The ID of the Google Cloud project.
        zone (str): The zone of the reservation.
        reservation_name (str): The name of the reservation to delete.
    Returns:
        The operation response from the reservation deletion request.
    """

    client = compute_v1.ReservationsClient()

    operation = client.delete(
        project=project_id,
        zone=zone,
        reservation=reservation_name,
    )

    wait_for_extended_operation(operation, "Reservation deletion")
    print(operation.status)
    # Example response:
    # Status.DONE
    return operation

REST

如要刪除預留項目,請向 reservation.delete 方法發出 DELETE 要求:

DELETE https://compute./compute/v1/projects/PROJECT_ID/zones/ZONE/reservations/RESERVATION_NAME

更改下列內容:

  • PROJECT_ID:您建立預留項目的專案 ID。

  • ZONE:預留項目所在的可用區。

  • RESERVATION_NAME:預留項目名稱。

後續步驟