Elimine reservas


Este documento explica como eliminar reservas. Para saber como eliminar pedidos de reserva futuros, consulte o artigo Cancele ou elimine pedidos de reserva futuros em alternativa.

Elimine uma reserva para deixar de incorrer em custos por recursos reservados de que já não precisa.

Limitações

Antes de eliminar uma reserva, considere o seguinte:

  • Só pode eliminar uma reserva partilhada no mesmo projeto em que a criou.

  • Só pode eliminar uma reserva especificamente segmentada se nenhuma instância do Compute Engine a consumir. Se alguma instância consumir a reserva, antes de a eliminar, faça uma das seguintes ações:

    • Elimine as instâncias

    • Parar ou suspender as instâncias

  • Só pode eliminar uma reserva criada automaticamente para uma reserva futura após o respetivo período de reserva terminar.

  • Só pode eliminar uma reserva associada a um compromisso se a desassociar primeiro substituindo a reserva.

Antes de começar

  • Se ainda não o tiver feito, configure a autenticação. A autenticação valida a sua identidade para aceder a Google Cloud serviços e APIs. Para executar código ou exemplos a partir de um ambiente de desenvolvimento local, pode autenticar-se no Compute Engine selecionando uma das seguintes opções:

    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. Instale a CLI Google Cloud. Após a instalação, inicialize a CLI gcloud executando o seguinte comando:

      gcloud init

      Se estiver a usar um fornecedor de identidade (IdP) externo, primeiro tem de iniciar sessão na CLI gcloud com a sua identidade federada.

    2. Set a default region and zone.

    Go

    Para usar os Go exemplos nesta página num ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e, em seguida, configure as Credenciais predefinidas da aplicação com as suas credenciais de utilizador.

      Instale a CLI Google Cloud.

      Se estiver a usar um fornecedor de identidade (IdP) externo, primeiro tem de iniciar sessão na CLI gcloud com a sua identidade federada.

      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.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Para mais informações, consulte Set up authentication for a local development environment.

    Java

    Para usar os Java exemplos nesta página num ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e, em seguida, configure as Credenciais predefinidas da aplicação com as suas credenciais de utilizador.

      Instale a CLI Google Cloud.

      Se estiver a usar um fornecedor de identidade (IdP) externo, primeiro tem de iniciar sessão na CLI gcloud com a sua identidade federada.

      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.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Para mais informações, consulte Set up authentication for a local development environment.

    Node.js

    Para usar os Node.js exemplos nesta página num ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e, em seguida, configure as Credenciais predefinidas da aplicação com as suas credenciais de utilizador.

      Instale a CLI Google Cloud.

      Se estiver a usar um fornecedor de identidade (IdP) externo, primeiro tem de iniciar sessão na CLI gcloud com a sua identidade federada.

      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.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Para mais informações, consulte Set up authentication for a local development environment.

    Python

    Para usar os Python exemplos nesta página num ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e, em seguida, configure as Credenciais predefinidas da aplicação com as suas credenciais de utilizador.

      Instale a CLI Google Cloud.

      Se estiver a usar um fornecedor de identidade (IdP) externo, primeiro tem de iniciar sessão na CLI gcloud com a sua identidade federada.

      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.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Para mais informações, consulte Set up authentication for a local development environment.

    REST

    Para usar os exemplos da API REST nesta página num ambiente de desenvolvimento local, usa as credenciais que fornece à CLI gcloud.

      Instale a CLI Google Cloud.

      Se estiver a usar um fornecedor de identidade (IdP) externo, primeiro tem de iniciar sessão na CLI gcloud com a sua identidade federada.

    Para mais informações, consulte o artigo Autenticar para usar REST na Google Cloud documentação de autenticação.

Funções necessárias

Para receber a autorização de que precisa para eliminar reservas, peça ao seu administrador para lhe conceder a função de IAM Administrador do Compute (roles/compute.admin) no projeto. Para mais informações sobre a atribuição de funções, consulte o artigo Faça a gestão do acesso a projetos, pastas e organizações.

Esta função predefinida contém a autorização compute.reservations.delete , que é necessária para eliminar reservas.

Também pode obter esta autorização com funções personalizadas ou outras funções predefinidas.

Elimine uma reserva

Se eliminar uma reserva que possa ser consumida automaticamente por quaisquer instâncias de computação correspondentes, todas as instâncias que consumam a reserva eliminada continuam a ser executadas. Continua a incorrer em custos por essas instâncias.

Pode eliminar reservas individuais ou várias reservas em simultâneo. Para várias reservas, use a Google Cloud consola. Para reservas únicas, selecione qualquer uma das seguintes opções:

Consola

  1. Na Google Cloud consola, aceda à página Reservas.

    Aceda a Reservas

  2. No separador Reservas a pedido (predefinição), selecione as reservas que quer eliminar.

  3. Clique em Eliminar.

  4. Para confirmar, clique em Eliminar.

gcloud

Para eliminar uma reserva, use o comando gcloud compute reservations delete:

gcloud compute reservations delete RESERVATION_NAME \
    --zone=ZONE

Substitua o seguinte:

  • RESERVATION_NAME: o nome da reserva.

  • ZONE: a zona onde existe a reserva.

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

Para eliminar uma reserva, faça um DELETE pedido ao método reservation.delete:

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

Substitua o seguinte:

  • PROJECT_ID: o ID do projeto onde criou a reserva.

  • ZONE: a zona onde existe a reserva.

  • RESERVATION_NAME: o nome da reserva.

O que se segue?