Elimine uma imagem personalizada


Só pode eliminar imagens personalizadas que tenha adicionado ou que tenham sido adicionadas por alguém com acesso ao projeto.

Se quiser manter uma cópia de segurança da imagem, exporte a imagem personalizada para o Cloud Storage antes de a eliminar.

Antes de começar

  • Leia o documento Imagens.
  • 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.

    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.

Elimine uma imagem personalizada

Use um dos seguintes métodos para eliminar a imagem.

Consola

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

    Aceder a Imagens

  2. Selecione a caixa à esquerda da imagem que quer eliminar.

  3. Clique em Eliminar na parte superior da página. A sua imagem é eliminada.

gcloud

Use o comando gcloud compute images delete para eliminar uma imagem:

gcloud compute images delete IMAGE_NAME

Substitua IMAGE_NAME pelo nome da imagem a eliminar.

Go

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

Faça um pedido POST ao método images().delete. Especifique o nome da imagem que quer eliminar.

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

Substitua o seguinte:

  • PROJECT_ID: o projeto ao qual a imagem pertence.
  • RESOURCE_ID: o nome da imagem que quer eliminar.