Delete a Compute Engine instance Stay organized with collections Save and categorize content based on your preferences.
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
- If you haven't already, set upauthentication. Authentication verifies your identity for access to Google Cloud services and APIs. To run code or samples from a local development environment, you can authenticate to Compute Engine by selecting one of the following options:
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
Install the Google Cloud CLI. After installation,initialize the Google Cloud CLI by running the following command:
gcloudinit
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.- Set a default region and zone.
C#
To use the .NET samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
For more information, see Set up authentication for a local development environment.
Go
To use the Go samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
For more information, see Set up authentication for a local development environment.
Java
To use the Java samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
For more information, see Set up authentication for a local development environment.
Node.js
To use the Node.js samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
For more information, see Set up authentication for a local development environment.
PHP
To use the PHP samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
For more information, see Set up authentication for a local development environment.
Python
To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
For more information, see Set up authentication for a local development environment.
Ruby
To use the Ruby samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
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.
For more information, see Set up authentication for a local development environment.
REST
To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.For more information, seeAuthenticate for using REST in the Google Cloud authentication documentation.
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.deleteon the instance- To force the deletion of an attached disk:
compute.disks.deleteon 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:
To preserve a GPU attached to an N1 virtual machine (VM) instance,remove the GPU from the VM.
To preserve an attached disk, do one of the following:
To preserve a boot disk,detach the boot disk from the instance.
To preserve a boot or non-boot disk, set theauto-delete setting of the disk to
false.
To preserve the data of a Local SSD disk, copy the data of the disk to apersistentstorage option.
To reuse the static external IP address of an instance,unassign the IP address.
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
This option deletes the instances and deletes, or forces the deletion of,boot, non-boot, or all attached disks.
Delete instances and preserve disks
This option deletes the instances but preserves boot, non-boot, or allattached disks for later use.
Delete instances and all attached resources
Depending on what you want to do when deleting a compute instance, use thefollowing options:
If youconfigured an attached disk to be preservedupon instance deletion, then you can override this setting and force itsdeletion using the Google Cloud CLI.
Caution: Forcefully deleting a disk that is attached to an instance alsodeletes all its instant snapshots. You can't recover these snapshots. Toretain the data in an instant snapshot,create a standard snapshot from itbefore deleting the instance.If you've enabledgraceful shutdown inthe instance, then you can delete the instance without gracefully shuttingit down or end an ongoing graceful shutdown using the Google Cloud console,gcloud CLI, or REST API.
To delete multiple instances simultaneously, use the Google Cloud consoleor, for instances located in the same zone, the gcloud CLI.
To delete one or more instances and all attached resources, select one of thefollowing options:
Console
In the Google Cloud console, go to theVM instances page.
Select the instances that you want to delete.
ClickDelete.
In the dialog, do the following:
Optional: To delete the instances without gracefully shut them down,or end an ongoing graceful shutdown, select theSkip graceful shutdown (if applicable) checkbox.
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=ZONEReplace 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:
To force the deletion of the disks attached to one or more instances,include the
--delete-disksflag:gcloud compute instances deleteINSTANCE_NAMES \--delete-disks=DELETE_DISK_TYPE \ --zone=ZONEReplace
DELETE_DISK_TYPEwith one of the followingvalues:To delete attached boot and non-boot persistent storage:
allTo delete only attached boot persistent storage:
bootTo delete only non-boot persistent storage:
data
If you've enabled graceful shutdown in one or more instances, then youcan delete the instances without gracefully shutting them down, ormanually end an ongoing graceful shutdown. To do so, use the
gcloud beta compute instances deletecommandwith the--no-graceful-shutdownflag:Preview — The
--no-graceful-shutdownflagThis 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 deleteINSTANCE_NAMES \--no-graceful-shutdown \ --zone=ZONE
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:",eendendREST
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_NAMEReplace 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 — The 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.noGracefulShutdown query parameter
DELETE https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME?noGracefulShutdown=trueDelete 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=ZONEReplace 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:
allTo preserve only attached boot persistent storage:
bootTo 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=ZONEWhat'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.