Delete a Compute Engine instance

This document explains how to delete a Compute Engine instance. To learn moreabout the lifecycle of an instance, seeCompute Engine instance lifecycle.

If you no longer need an instance, then delete it to stop incurring charges forthe instance and its attached resources.

Caution: If you delete an instance in a managed instance group (MIG) that usesautoscaler, then the MIG may automatically create a new instance to replace thedeleted instance. To prevent this,resize the MIGorreconfigure its autoscaler.

Before you begin

Required roles

To get the permissions that you need to delete a compute instance, ask your administrator to grant you theCompute Instance Admin (v1) (roles/compute.instanceAdmin.v1) IAM role on the project. For more information about granting roles, seeManage access to projects, folders, and organizations.

This predefined role contains the permissions required to delete a compute instance. To see the exact permissions that are required, expand theRequired permissions section:

Required permissions

The following permissions are required to delete a compute instance:

  • compute.instances.delete on the instance
  • To force the deletion of an attached disk: compute.disks.delete on the disk

You might also be able to get these permissions withcustom roles or otherpredefined roles.

Billing implications

After you delete a compute instance, you stop incurring charges for the instanceand its attached resources, except in the following cases:

  • If you delete an instance that is hosted on asole-tenant node, then you still incur charges forthe sole-tenant node.

  • If you delete an instance that is using areservation, then youcontinue to pay for the reserved resources until one of the followingoccurs:

    • Compute Engine automatically deletes the reservation at yourchosen date and time.

    • You delete the reservation.

    • You reduce the number of reserved instances in the reservation.

  • If you have acommitted use discount,then you continue to pay for the committed resources, regardless if you usethem or not.

  • If you preserve any resources attached to the instance, such as disks, thenyou continue to pay for those resources until you delete them.

For more information, seeVM instances pricing.

Preserve attached resources

In some cases, before you delete a compute instance, you might want to preserveone of its attached resources. You can preserve attached resources by doing thefollowing:

Delete instances

When you delete a compute instance, Compute Enginestops the instancebefore deleting it.

If you delete one or more instances simultaneously, then you must decide whathappens to the attached disks:

Delete instances and all attached resources

Depending on what you want to do when deleting a compute instance, use thefollowing options:

To delete one or more instances and all attached resources, select one of thefollowing options:

Console

  1. In the Google Cloud console, go to theVM instances page.

    Go to VM instances

  2. Select the instances that you want to delete.

  3. ClickDelete.

  4. In the dialog, do the following:

    1. Optional: To delete the instances without gracefully shut them down,or end an ongoing graceful shutdown, select theSkip graceful shutdown (if applicable) checkbox.

    2. To confirm, clickDelete.

gcloud

To delete one or more instances in the same zone, use thegcloud compute instances delete command:

gcloud compute instances deleteINSTANCE_NAMES \    --zone=ZONE

Replace the following:

  • INSTANCE_NAMES: a list of instance names separated byspaces—for example,instance-01 instance-02 instance-03.

  • ZONE: the zone where the instances are located.

Optionally, you can do one or both of the following:

C#

usingGoogle.Cloud.Compute.V1;usingSystem.Threading.Tasks;publicclassDeleteInstanceAsyncSample{publicasyncTaskDeleteInstanceAsync(// TODO(developer): Set your own default values for these parameters or pass different values when calling this method.stringprojectId="your-project-id",stringzone="us-central1-a",stringmachineName="test-machine"){// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests.InstancesClientclient=awaitInstancesClient.CreateAsync();// Make the request to delete a VM instance.varinstanceDeletion=awaitclient.DeleteAsync(projectId,zone,machineName);// Wait for the operation to complete using client-side polling.awaitinstanceDeletion.PollUntilCompletedAsync();}}

Go

import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb")// deleteInstance sends a delete request to the Compute Engine API and waits for it to complete.funcdeleteInstance(wio.Writer,projectID,zone,instanceNamestring)error{// projectID := "your_project_id"// zone := "europe-central2-b"// instanceName := "your_instance_name"ctx:=context.Background()instancesClient,err:=compute.NewInstancesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewInstancesRESTClient: %w",err)}deferinstancesClient.Close()req:=&computepb.DeleteInstanceRequest{Project:projectID,Zone:zone,Instance:instanceName,}op,err:=instancesClient.Delete(ctx,req)iferr!=nil{returnfmt.Errorf("unable to delete instance: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance deleted\n")returnnil}

Java

importcom.google.api.gax.longrunning.OperationFuture;importcom.google.cloud.compute.v1.DeleteInstanceRequest;importcom.google.cloud.compute.v1.InstancesClient;importcom.google.cloud.compute.v1.Operation;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassDeleteInstance{publicstaticvoidmain(String[]args)throwsIOException,InterruptedException,ExecutionException,TimeoutException{// TODO(developer): Replace these variables before running the sample.Stringproject="your-project-id";Stringzone="zone-name";StringinstanceName="instance-name";deleteInstance(project,zone,instanceName);}// Delete the instance specified by `instanceName`// if it's present in the given project and zone.publicstaticvoiddeleteInstance(Stringproject,Stringzone,StringinstanceName)throwsIOException,InterruptedException,ExecutionException,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 `instancesClient.close()` method on the client to safely// clean up any remaining background resources.try(InstancesClientinstancesClient=InstancesClient.create()){System.out.printf("Deleting instance: %s ",instanceName);// Describe which instance is to be deleted.DeleteInstanceRequestdeleteInstanceRequest=DeleteInstanceRequest.newBuilder().setProject(project).setZone(zone).setInstance(instanceName).build();OperationFuture<Operation,Operation>operation=instancesClient.deleteAsync(deleteInstanceRequest);// Wait for the operation to complete.Operationresponse=operation.get(3,TimeUnit.MINUTES);if(response.hasError()){System.out.println("Instance deletion failed ! ! "+response);return;}System.out.println("Operation Status: "+response.getStatus());}}}

Node.js

/** * TODO(developer): Uncomment these variables before running the sample. */// const projectId = 'YOUR_PROJECT_ID';// const zone = 'europe-central2-b'// const instanceName = 'YOUR_INSTANCE_NAME';constcompute=require('@google-cloud/compute');// Delete the instance specified by `instanceName` if it's present in the given project and zone.asyncfunctiondeleteInstance(){constinstancesClient=newcompute.InstancesClient();console.log(`Deleting${instanceName} from${zone}...`);const[response]=awaitinstancesClient.delete({project:projectId,zone,instance:instanceName,});letoperation=response.latestResponse;constoperationsClient=newcompute.ZoneOperationsClient();// Wait for the delete operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log('Instance deleted.');}deleteInstance();

PHP

use Google\Cloud\Compute\V1\Client\InstancesClient;use Google\Cloud\Compute\V1\DeleteInstanceRequest;/** * Delete an instance. * * @param string $projectId Your Google Cloud project ID. * @param string $zone Zone where the instance you want to delete is (like "us-central1-a"). * @param string $instanceName Unique name for the Compute instance to delete. * * @throws \Google\ApiCore\ApiException if the remote call fails. * @throws \Google\ApiCore\ValidationException if local error occurs before remote call. */function delete_instance(    string $projectId,    string $zone,    string $instanceName) {    // Delete the Compute Engine instance using InstancesClient.    $instancesClient = new InstancesClient();    $request = (new DeleteInstanceRequest())        ->setInstance($instanceName)        ->setProject($projectId)        ->setZone($zone);    $operation = $instancesClient->delete($request);    // Wait for the operation to complete.    $operation->pollUntilComplete();    if ($operation->operationSucceeded()) {        printf('Deleted instance %s' . PHP_EOL, $instanceName);    } else {        $error = $operation->getError();        printf('Failed to delete instance: %s' . PHP_EOL, $error?->getMessage());    }}

Python

from__future__importannotationsimportsysfromtypingimportAnyfromgoogle.api_core.extended_operationimportExtendedOperationfromgoogle.cloudimportcompute_v1defwait_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)ifoperation.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)raiseoperation.exception()orRuntimeError(operation.error_message)ifoperation.warnings:print(f"Warnings during{verbose_name}:\n",file=sys.stderr,flush=True)forwarninginoperation.warnings:print(f" -{warning.code}:{warning.message}",file=sys.stderr,flush=True)returnresultdefdelete_instance(project_id:str,zone:str,machine_name:str)->None:"""    Send an instance deletion request to the Compute Engine API and wait for it to complete.    Args:        project_id: project ID or project number of the Cloud project you want to use.        zone: name of the zone you want to use. For example: “us-west3-b”        machine_name: name of the machine you want to delete.    """instance_client=compute_v1.InstancesClient()print(f"Deleting{machine_name} from{zone}...")operation=instance_client.delete(project=project_id,zone=zone,instance=machine_name)wait_for_extended_operation(operation,"instance deletion")print(f"Instance{machine_name} deleted.")

Ruby

require"google/cloud/compute/v1"# Sends an instance deletion request to the Compute Engine API and waits for it to complete.## @param [String] project project ID or project number of the Cloud project you want to use.# @param [String] zone name of the zone you want to use. For example: "us-west3-b"# @param [String] instance_name name of the instance you want to delete.defdelete_instanceproject:,zone:,instance_name:# Initialize client that will be used to send requests. This client only needs to be created# once, and can be reused for multiple requests.client=::Google::Cloud::Compute::V1::Instances::Rest::Client.newputs"Deleting#{instance_name} from#{zone}..."begin# Make the request to delete a VM instance.operation=client.deleteproject:project,zone:zone,instance:instance_name# Wait for the delete operation to complete.operation=wait_until_doneoperation:operationifoperation.error?warn"Error during deletion:",operation.errorelsecompute_operation=operation.operationwarn"Warning during creation:",compute_operation.warningsunlesscompute_operation.warnings.empty?puts"Instance#{instance_name} deleted."endrescue::Google::Cloud::Error=>ewarn"Exception during deletion:",eendend

REST

To delete an instance, make aDELETE request to theinstances delete method:

DELETE https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME

Replace the following:

  • PROJECT_ID: the ID of the project where the instanceis located.

  • ZONE: the zone of the instance.

  • INSTANCE_NAME: the instance name.

Optionally, if you've enabled graceful shutdown in the instance, you candelete the instances without gracefully shutting it down, or manually end anongoing graceful shutdown. To do so, make aDELETE request to thebetainstances.delete method.In the request URL, include thenoGracefulShutdown query parameter set totrue:

Preview — ThenoGracefulShutdown query parameter

This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.

DELETE https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME?noGracefulShutdown=true

Delete instances and preserve disks

By default, deleting a compute instance deletes the instance and its attachedresources. However, when you delete an instance using the gcloud CLI,you can specify to preserve the attached disks, regardless of theirauto-delete settings.

To delete one or more instances in the same zone while preserving their attacheddisks, use thegcloud compute instances delete commandwith the--keep-disks flag:

gcloud compute instances deleteINSTANCE_NAMES \    --keep-disks=KEEP_DISK_TYPE \    --zone=ZONE

Replace the following:

  • INSTANCE_NAMES: a list of instance names separated byspaces—for example,instance-01 instance-02 instance-03.

  • KEEP_DISK_TYPE: specify one of the following values:

    • To preserve attached boot and non-boot persistent storage:all

    • To preserve only attached boot persistent storage:boot

    • To preserve only attached non-boot persistent storage:data

  • ZONE: the zone where the instances are located.

Optionally, if you've enabledgraceful shutdown in oneor more instances, you can delete the instances without gracefully shutting themdown, or manually end an ongoing graceful shutdown. To do so, use thegcloud beta compute instances delete commandwith the--no-graceful-shutdown flag:

Preview — The `--no-graceful-shutdown` flag

This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.

gcloud beta compute instances deleteVM_NAMES \    --keep-disks=KEEP_DISK_TYPE \--no-graceful-shutdown \    --zone=ZONE

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.