Elimina un'immagine personalizzata

Puoi eliminare solo le immagini personalizzate che hai aggiunto tu o un'altra persona che ha accesso al progetto.

Se vuoi conservare un backup dell'immagine, esporta l'immagine personalizzata in Cloud Storage prima di eliminarla.

Prima di iniziare

  • Leggi il documento Immagini.
  • Se non l'hai ancora fatto, configura l'autenticazione. L'autenticazione verifica la tua identità per l'accesso ad API e servizi Google Cloud . Per eseguire codice o esempi da un ambiente di sviluppo locale, puoi autenticarti in Compute Engine selezionando una delle seguenti opzioni:

    Seleziona la scheda relativa alla modalità di utilizzo degli esempi in questa pagina:

    Console

    Quando utilizzi la Google Cloud console per accedere a Google Cloud servizi e API, non devi configurare l'autenticazione.

    gcloud

    1. Installa Google Cloud CLI. Dopo l'installazione, inizializza Google Cloud CLI eseguendo il seguente comando:

      gcloud init

      Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

  • Imposta una regione e una zona predefinite.
  • Python

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

    1. Installa Google Cloud CLI.

    2. Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

    3. Se utilizzi una shell locale, crea le credenziali di autenticazione locali per il tuo account utente:

      gcloud auth application-default login

      Non devi eseguire questa operazione se utilizzi Cloud Shell.

      Se viene restituito un errore di autenticazione e utilizzi un provider di identità (IdP) esterno, verifica di aver acceduto a gcloud CLI con la tua identità federata.

    Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

    REST

    Per utilizzare gli esempi di API REST in questa pagina in un ambiente di sviluppo locale, utilizzi le credenziali che fornisci a gcloud CLI.

      Installa Google Cloud CLI.

      Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

    Per saperne di più, consulta Autenticati per usare REST nella Google Cloud documentazione sull'autenticazione di.

Elimina un'immagine personalizzata

Utilizza uno dei seguenti metodi per eliminare l'immagine.

Console

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

    Vai a Google Immagini

  2. Seleziona la casella a sinistra dell'immagine che vuoi eliminare.

  3. Fai clic su Elimina nella parte superiore della pagina. L'immagine viene eliminata.

gcloud

Utilizza il gcloud compute images delete comando per eliminare un'immagine:

gcloud compute images delete IMAGE_NAME

Sostituisci IMAGE_NAME con il nome dell'immagine da eliminare.

Vai

import (
	"context"
	"fmt"
	"io"

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

// Deletes the specified disk image
func deleteDiskImage(
	w io.Writer,
	projectID, imageName string,
) error {
	// projectID := "your_project_id"
	// imageName := "your_image"

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

	req := computepb.DeleteImageRequest{
		Image:   imageName,
		Project: projectID,
	}

	op, err := imagesClient.Delete(ctx, &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 deleted\n", imageName)

	return nil
}

Java


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

public class DeleteImage {

  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 use.
    String project = "your-project-id";
    // Name of the image you want to delete.
    String imageName = "your-image-name";

    deleteImage(project, imageName);
  }

  // Deletes a disk image.
  public static void deleteImage(String project, String imageName)
      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. After completing all of your requests, call
    // the `imagesClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ImagesClient imagesClient = ImagesClient.create()) {
      Operation response = imagesClient.deleteAsync(project, imageName).get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        System.out.println("Image deletion failed ! ! " + response);
        return;
      }
      System.out.printf("Operation Status for Image Name %s: %s ", imageName, response.getStatus());
    }
  }
}

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_image(project_id: str, image_name: str) -> None:
    """
    Deletes a disk image.

    Args:
        project_id: project ID or project number of the Cloud project you use.
        image_name: name of the image you want to delete.
    """
    image_client = compute_v1.ImagesClient()
    operation = image_client.delete(project=project_id, image=image_name)
    wait_for_extended_operation(operation, "image deletion")

REST

Effettua una POST richiesta al images().delete metodo. Specifica il nome dell'immagine che vuoi eliminare.

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

Sostituisci quanto segue:

  • PROJECT_ID: il progetto a cui appartiene l'immagine.
  • RESOURCE_ID: il nome dell'immagine che vuoi eliminare.