Elimina prenotazioni


Questo documento spiega come eliminare le prenotazioni. Per scoprire come eliminare le richieste di prenotazione future, consulta Annullare o eliminare le richieste di prenotazione future.

Elimina una prenotazione per interrompere gli addebiti per le risorse riservate di cui non hai più bisogno.

Limitazioni

Prima di eliminare una prenotazione, tieni presente quanto segue:

  • Puoi eliminare una prenotazione condivisa solo nello stesso progetto in cui l'hai creata.

  • Puoi eliminare una prenotazione con targeting specifico solo se non viene utilizzata da nessuna istanza Compute Engine. Se alcune istanze utilizzano la prenotazione, prima di eliminarla, esegui una delle seguenti operazioni:

    • Elimina le istanze

    • Arresta o sospendi le istanze

  • Puoi eliminare una prenotazione creata automaticamente per una prenotazione futura solo al termine del relativo periodo di prenotazione.

  • Puoi eliminare una prenotazione associata a un impegno solo se prima la scolleghi sostituendola.

Prima di iniziare

  • Se non l'hai ancora fatto, configura l'autenticazione. L'autenticazione è il processo mediante il quale la tua identità viene verificata per l'accesso a servizi e API. Google Cloud Per eseguire codice o esempi da un ambiente di sviluppo locale, puoi autenticarti su Compute Engine selezionando una delle seguenti opzioni:

    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. Vai

      Per utilizzare gli Go esempi in questa pagina in un ambiente di sviluppo locale, installa e inizializza l'interfaccia a riga di comando gcloud, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

      Per ulteriori informazioni, consulta Set up authentication for a local development environment.

      Java

      Per utilizzare gli Java esempi in questa pagina in un ambiente di sviluppo locale, installa e inizializza l'interfaccia a riga di comando gcloud, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

      Per ulteriori informazioni, consulta Set up authentication for a local development environment.

      Node.js

      Per utilizzare gli Node.js esempi in questa pagina in un ambiente di sviluppo locale, installa e inizializza l'interfaccia a riga di comando gcloud, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

      Per ulteriori informazioni, consulta Set up authentication for a local development environment.

      Python

      Per utilizzare gli Python esempi in questa pagina in un ambiente di sviluppo locale, installa e inizializza l'interfaccia a riga di comando gcloud, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

      Per ulteriori informazioni, consulta Set up authentication for a local development environment.

      REST

      Per utilizzare gli esempi dell'API REST in questa pagina in un ambiente di sviluppo locale, utilizza le credenziali fornite a gcloud CLI.

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

        gcloud init

      Per ulteriori informazioni, consulta Eseguire l'autenticazione per l'utilizzo di REST nella documentazione Google Cloud sull'autenticazione.

Ruoli obbligatori

Per ottenere l'autorizzazione necessaria per eliminare le prenotazioni, chiedi all'amministratore di concederti il ruolo IAM Amministratore di Compute (roles/compute.admin) nel progetto. Per saperne di più sulla concessione dei ruoli, consulta Gestire l'accesso a progetti, cartelle e organizzazioni.

Questo ruolo predefinito contiene l'autorizzazione compute.reservations.delete necessaria per eliminare le prenotazioni.

Potresti anche ottenere questa autorizzazione con ruoli personalizzati o altri ruoli predefiniti.

Eliminazione di una prenotazione

Se elimini una prenotazione che può essere utilizzata automaticamente da qualsiasi istanza di calcolo corrispondente, tutte le istanze che utilizzano la prenotazione eliminata continuano a funzionare. Continuerai a ricevere gli addebiti per queste istanze.

Puoi eliminare singole prenotazioni o più prenotazioni contemporaneamente. Per più prenotazioni, utilizza la console Google Cloud. Per le prenotazioni singole, seleziona una delle seguenti opzioni:

Console

  1. Nella console Google Cloud, vai alla pagina Prenotazioni.

    Vai a Prenotazioni

  2. Nella scheda Prenotazioni on demand (predefinita), seleziona le prenotazioni che vuoi eliminare.

  3. Fai clic su Elimina.

  4. Per confermare, fai clic su Elimina.

gcloud

Per eliminare una prenotazione, utilizza il comando gcloud compute reservations delete:

gcloud compute reservations delete RESERVATION_NAME \
    --zone=ZONE

Sostituisci quanto segue:

  • RESERVATION_NAME: il nome della prenotazione.

  • ZONE: la zona in cui esiste la prenotazione.

Vai

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

Per eliminare una prenotazione, invia una richiesta DELETE al metodo reservation.delete:

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

Sostituisci quanto segue:

  • PROJECT_ID: l'ID del progetto in cui hai creato la prenotazione.

  • ZONE: la zona in cui esiste la prenotazione.

  • RESERVATION_NAME: il nome della prenotazione.

Passaggi successivi