Delete a disk image
Stay organized with collections
Save and categorize content based on your preferences.
Delete a disk image from the specified project.
Explore further
For detailed documentation that includes this code sample, see the following:
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License
, and code samples are licensed under the Apache 2.0 License
. For details, see the Google Developers Site Policies
. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis page provides code samples in Go, Java, and Python for deleting a disk image from a specified Google Cloud project.\u003c/p\u003e\n"],["\u003cp\u003eEach code sample requires prior setup of the respective language environment and authentication via Application Default Credentials as described in the documentation.\u003c/p\u003e\n"],["\u003cp\u003eThe code snippets demonstrate how to use the Compute Engine API client libraries to delete a disk image using the image name and project ID.\u003c/p\u003e\n"],["\u003cp\u003eThe process for deleting an image with the code snippets in this page results in an operation that you will need to wait for, as they are all asynchronous.\u003c/p\u003e\n"],["\u003cp\u003eFurther information on the code samples is available in the corresponding API reference documentation and the sample browser.\u003c/p\u003e\n"]]],[],null,["# Delete a disk image from the specified project.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Delete a custom image](/compute/docs/images/delete-custom)\n\nCode sample\n-----------\n\n### Go\n\n\nBefore trying this sample, follow the Go setup instructions in the\n[Compute Engine quickstart using\nclient libraries](/compute/docs/api/using-libraries).\n\n\nFor more information, see the\n[Compute Engine Go API\nreference documentation](/go/docs/reference/cloud.google.com/go/compute/latest/apiv1).\n\n\nTo authenticate to Compute Engine, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"io\"\n\n \tcompute \"cloud.google.com/go/compute/apiv1\"\n \tcomputepb \"cloud.google.com/go/compute/apiv1/computepb\"\n )\n\n // Deletes the specified disk image\n func deleteDiskImage(\n \tw io.Writer,\n \tprojectID, imageName string,\n ) error {\n \t// projectID := \"your_project_id\"\n \t// imageName := \"your_image\"\n\n \tctx := context.Background()\n \timagesClient, err := compute.https://cloud.google.com/go/docs/reference/cloud.google.com/go/compute/latest/apiv1.html#cloud_google_com_go_compute_apiv1_ImagesClient_NewImagesRESTClient(ctx)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"NewImagesRESTClient: %w\", err)\n \t}\n \tdefer imagesClient.Close()\n\n \treq := computepb.DeleteImageRequest{\n \t\tImage: imageName,\n \t\tProject: projectID,\n \t}\n\n \top, err := imagesClient.Delete(ctx, &req)\n\n \tif err = op.Wait(ctx); err != nil {\n \t\treturn fmt.Errorf(\"unable to wait for the operation: %w\", err)\n \t}\n\n \tfmt.Fprintf(w, \"Disk image %s deleted\\n\", imageName)\n\n \treturn nil\n }\n\n### Java\n\n\nBefore trying this sample, follow the Java setup instructions in the\n[Compute Engine quickstart using\nclient libraries](/compute/docs/api/using-libraries).\n\n\nFor more information, see the\n[Compute Engine Java API\nreference documentation](/java/docs/reference/google-cloud-compute/latest/overview).\n\n\nTo authenticate to Compute Engine, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n import com.google.cloud.compute.v1.https://cloud.google.com/java/docs/reference/google-cloud-compute/latest/com.google.cloud.compute.v1.ImagesClient.html;\n import com.google.cloud.compute.v1.https://cloud.google.com/java/docs/reference/google-cloud-compute/latest/com.google.cloud.compute.v1.Operation.html;\n import java.io.IOException;\n import java.util.concurrent.ExecutionException;\n import java.util.concurrent.TimeUnit;\n import java.util.concurrent.TimeoutException;\n\n public class DeleteImage {\n\n public static void main(String[] args)\n throws IOException, ExecutionException, InterruptedException, TimeoutException {\n // TODO(developer): Replace these variables before running the sample.\n // Project ID or project number of the Cloud project you use.\n String project = \"your-project-id\";\n // Name of the image you want to delete.\n String imageName = \"your-image-name\";\n\n deleteImage(project, imageName);\n }\n\n // Deletes a disk image.\n public static void deleteImage(String project, String imageName)\n throws IOException, ExecutionException, InterruptedException, TimeoutException {\n // Initialize client that will be used to send requests. This client only needs to be created\n // once, and can be reused for multiple requests. After completing all of your requests, call\n // the `imagesClient.close()` method on the client to safely\n // clean up any remaining background resources.\n try (https://cloud.google.com/java/docs/reference/google-cloud-compute/latest/com.google.cloud.compute.v1.ImagesClient.html imagesClient = https://cloud.google.com/java/docs/reference/google-cloud-compute/latest/com.google.cloud.compute.v1.ImagesClient.html.create()) {\n https://cloud.google.com/java/docs/reference/google-cloud-compute/latest/com.google.cloud.compute.v1.Operation.html response = imagesClient.deleteAsync(project, imageName).get(3, TimeUnit.MINUTES);\n\n if (response.https://cloud.google.com/java/docs/reference/google-cloud-compute/latest/com.google.cloud.compute.v1.Operation.html#com_google_cloud_compute_v1_Operation_hasError__()) {\n System.out.println(\"Image deletion failed ! ! \" + response);\n return;\n }\n System.out.printf(\"Operation Status for Image Name %s: %s \", imageName, response.https://cloud.google.com/java/docs/reference/google-cloud-compute/latest/com.google.cloud.compute.v1.Operation.html#com_google_cloud_compute_v1_Operation_getStatus__());\n }\n }\n }\n\n### Python\n\n\nBefore trying this sample, follow the Python setup instructions in the\n[Compute Engine quickstart using\nclient libraries](/compute/docs/api/using-libraries).\n\n\nFor more information, see the\n[Compute Engine Python API\nreference documentation](/python/docs/reference/compute/latest).\n\n\nTo authenticate to Compute Engine, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n from __future__ import annotations\n\n import sys\n from typing import Any\n\n from google.api_core.extended_operation import ExtendedOperation\n from google.cloud import https://cloud.google.com/python/docs/reference/compute/latest/\n\n\n def wait_for_extended_operation(\n operation: ExtendedOperation, verbose_name: str = \"operation\", timeout: int = 300\n ) -\u003e Any:\n \"\"\"\n Waits for the extended (long-running) operation to complete.\n\n If the operation is successful, it will return its result.\n If the operation ends with an error, an exception will be raised.\n If there were any warnings during the execution of the operation\n they will be printed to sys.stderr.\n\n Args:\n operation: a long-running operation you want to wait on.\n verbose_name: (optional) a more verbose name of the operation,\n used only during error and warning reporting.\n timeout: how long (in seconds) to wait for operation to finish.\n If None, wait indefinitely.\n\n Returns:\n Whatever the operation.result() returns.\n\n Raises:\n This method will raise the exception received from `operation.exception()`\n or RuntimeError if there is no exception set, but there is an `error_code`\n set for the `operation`.\n\n In case of an operation taking longer than `timeout` seconds to complete,\n a `concurrent.futures.TimeoutError` will be raised.\n \"\"\"\n result = operation.result(timeout=timeout)\n\n if operation.error_code:\n print(\n f\"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}\",\n file=sys.stderr,\n flush=True,\n )\n print(f\"Operation ID: {operation.name}\", file=sys.stderr, flush=True)\n raise operation.exception() or RuntimeError(operation.error_message)\n\n if operation.warnings:\n print(f\"Warnings during {verbose_name}:\\n\", file=sys.stderr, flush=True)\n for warning in operation.warnings:\n print(f\" - {warning.code}: {warning.message}\", file=sys.stderr, flush=True)\n\n return result\n\n\n def delete_image(project_id: str, image_name: str) -\u003e None:\n \"\"\"\n Deletes a disk image.\n\n Args:\n project_id: project ID or project number of the Cloud project you use.\n image_name: name of the image you want to delete.\n \"\"\"\n image_client = https://cloud.google.com/python/docs/reference/compute/latest/.https://cloud.google.com/python/docs/reference/compute/latest/google.cloud.compute_v1.services.images.ImagesClient.html()\n operation = image_client.https://cloud.google.com/python/docs/reference/compute/latest/google.cloud.compute_v1.services.images.ImagesClient.html#google_cloud_compute_v1_services_images_ImagesClient_delete(project=project_id, image=image_name)\n wait_for_extended_operation(operation, \"image deletion\")\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=compute)."]]