Suspend or resume a Compute Engine instance Stay organized with collections Save and categorize content based on your preferences.
This document explains how to suspend or resume Compute Engine instances. Tolearn more about suspending, stopping, or resetting instances, seeSuspend, stop, or reset Compute Engine instances.
If you want to keep your Compute Engine instance around, but you don'twant to incur charges for it when the instance isn't in use, then you cansuspend the instance. Suspending an instance preserves the instance and migratesthe contents of the instance's memory to storage. After resuming the instance,Compute Engine migrates the instance's memory from storage back to theinstance, and the instance starts running again.
Suspending a Compute Engine instance is useful for the following:
Development and test environments that are not being fully used during offperiods, such as during evenings or weekends, and that you want to maintainfor costs saving or faster initialization than creating new instances.
Applications that require a long period of initialization after the instancehas finished booting, but before the application is ready to service itsfirst request, such as virtual developer workstations or complex Javaapplications.
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.
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.
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 suspend or resume a compute instance, ask your administrator to grant you theCompute Instance Admin (v1) (roles/compute.instanceAdmin.v1) IAM role on the instance. For more information about granting roles, seeManage access to projects, folders, and organizations.
This predefined role contains the permissions required to suspend or resume a compute instance. To see the exact permissions that are required, expand theRequired permissions section:
Required permissions
The following permissions are required to suspend or resume a compute instance:
- To suspend an instance:
compute.instances.suspend - To resume an instance:
compute.instances.resume
You might also be able to get these permissions withcustom roles or otherpredefined roles.
Limitations
When suspending a compute instance, the following limitations apply:
You can only suspend an instance if the guest OS supports it. For moreinformation, seeOperating system details.
You can only suspend an instance that uses Debian 8 or 9 as guest OS ifyouconfigure the OS before suspending theinstance.
You can only suspend an instance for up to 60 days beforeCompute Engine automatically transitions its state to
TERMINATED.You can suspend Spot VMs or preemptibleinstances—however, if Compute Engine preempts the instancebefore the suspend operation completes, Compute Engine ends thesuspend operation and preempts the instances.
You can't suspend instances with GPUs attached.
You can't suspend bare metal instances.
You can't suspend Confidential VMs.
You can't suspend instances by using the standard processes that arebuilt into their guest environment. Commands such as
systemctl suspendin Ubuntu 16.04 or later, aren't supported. If called, thenCompute Engine ignores the in-guest signal.You can't suspend instances with more than 208 GB of memory.
You can't suspend instances that have CSEK-protected disks attached.
Enable suspend operations in Debian 8 or 9
If a compute instance is running Debian 8 and 9 as its guest OS, then, beforesuspending the instance, you must enable suspend and resume operations by doingone of the following:
Recommended:Configure the ACPID
Configure the ACPID
To enable the suspend and resume operation in Debian 8 or 9, you can configuretheAdvanced Configuration and Power Interface events Daemon (ACPID)to handle the sleep button event. After enabling the deep sleep button event,you can add a shell script for handling the sleep event as described in thissection.
To configure the ACPID to support suspend and resume operations, do thefollowing:
If you haven't already, thenconnect to your Linux instance.
Create the
eventsfolder in theacpifolder:sudo mkdir -p /etc/acpi/events/Configure the ACPID to handle the sleep button event:
cat <<EOF | sudo tee /etc/acpi/events/sleepbtn-acpi-supportevent=button[ /]sleepaction=/etc/acpi/sleepbtn-acpi-support.shEOFCreate the sleep event handling script:
cat <<EOF | sudo tee /etc/acpi/sleepbtn-acpi-support.sh#!/bin/shecho mem > /sys/power/stateEOFSet up the permissions for the script:
sudo chmod 755 /etc/acpi/sleepbtn-acpi-support.shTo make the changes effective, restart the ACPID:
sudo systemctl restart acpid.service
Install D-Bus
To enable the suspend and resume operation in Debian 8 or 9, you can installD-Bus.
To install D-Bus in your compute instance's guest OS when the OS is using Debian8 or 9, do the following:
If you haven't already, thenconnect to your Linux instance.
Install D-Bus:
sudo apt-get install dbusTo make the changes effective, restart
logind:sudo systemctl restart systemd-logind.service
Suspend an instance
If the guest OS of your compute instance is using Debian 8 or 9, then, beforesuspending the instance, you mustconfigure the guest OS to support suspend and resumeoperations as described in this document.
To suspend an instance, use of the following methods based on whether theinstance has Local SSD disks attached:
If your instance doesn't have any Local SSD disks attached, then seeSuspend an instance without Local SSD disks.
If your instance has any Local SSD disks attached, and you want to eitherdiscard or preserve (Preview) the disks'Local SSD data, then seeSuspend an instance with Local SSD disks.
Suspend an instance without Local SSD disks
You can suspend multiple compute instances simultaneously or individualinstances. For multiple instances, use the Google Cloud console or, for instanceslocated in the same zone, the Google Cloud CLI. For individual instances, selectany of the following options:
Console
In the Google Cloud console, go to theVM instances page.
Select one or more instances to suspend.
ClickSuspend, and thenclickSuspend to confirm.
gcloud
To suspend one or more instances in a single zone, use thegcloud compute instances suspend command:
gcloud compute instances suspendINSTANCE_NAMES \ --zone=ZONEReplace the following:
INSTANCE_NAMES: a whitespace-separated list of namesof instances—for example,instance-01 instance-02 instance-03.ZONE: the zone where the instances are located.
Go
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb")// suspendInstance suspends a running Google Compute Engine instance.funcsuspendInstance(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.SuspendInstanceRequest{Project:projectID,Zone:zone,Instance:instanceName,}op,err:=instancesClient.Suspend(ctx,req)iferr!=nil{returnfmt.Errorf("unable to suspend instance: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance suspended\n")returnnil}Java
importcom.google.cloud.compute.v1.Instance.Status;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;publicclassSuspendInstance{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// project: project ID or project number of the Cloud project your instance belongs to.// zone: name of the zone your instance belongs to.// instanceName: name of the instance your want to suspend.Stringproject="your-project-id";Stringzone="zone-name";StringinstanceName="instance-name";suspendInstance(project,zone,instanceName);}// Suspend a running Google Compute Engine instance.// For limitations and compatibility on which instances can be suspended,// see: https://cloud.google.com/compute/docs/instances/suspend-resume-instance#limitationspublicstaticvoidsuspendInstance(Stringproject,Stringzone,StringinstanceName)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Instantiates a client.try(InstancesClientinstancesClient=InstancesClient.create()){Operationoperation=instancesClient.suspendAsync(project,zone,instanceName).get(300,TimeUnit.SECONDS);if(operation.hasError()||!instancesClient.get(project,zone,instanceName).getStatus().equalsIgnoreCase(Status.SUSPENDED.toString())){System.out.println("Cannot suspend instance. Try again!");return;}System.out.printf("Instance suspended successfully ! %s",instanceName);}}}Node.js
/** * TODO(developer): Uncomment and replace 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');// Suspends a running Google Compute Engine instance.asyncfunctionsuspendInstance(){constinstancesClient=newcompute.InstancesClient();const[response]=awaitinstancesClient.suspend({project:projectId,zone,instance:instanceName,});letoperation=response.latestResponse;constoperationsClient=newcompute.ZoneOperationsClient();// Wait for the create operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log('Instance suspended.');}suspendInstance();PHP
use Google\Cloud\Compute\V1\Client\InstancesClient;use Google\Cloud\Compute\V1\SuspendInstanceRequest;/** * Suspend a running Google Compute Engine instance. * * @param string $projectId Project ID or project number of the Cloud project your instance belongs to. * @param string $zone Name of the zone your instance belongs to. * @param string $instanceName Name of the instance you want to suspend. * * @throws \Google\ApiCore\ApiException if the remote call fails. * @throws \Google\ApiCore\ValidationException if local error occurs before remote call. */function suspend_instance( string $projectId, string $zone, string $instanceName) { // Suspend the running Compute Engine instance using InstancesClient. $instancesClient = new InstancesClient(); $request = (new SuspendInstanceRequest()) ->setInstance($instanceName) ->setProject($projectId) ->setZone($zone); $operation = $instancesClient->suspend($request); // Wait for the operation to complete. $operation->pollUntilComplete(); if ($operation->operationSucceeded()) { printf('Instance %s suspended successfully' . PHP_EOL, $instanceName); } else { $error = $operation->getError(); printf('Failed to suspend 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)returnresultdefsuspend_instance(project_id:str,zone:str,instance_name:str)->None:""" Suspend a running Google Compute Engine instance. Args: project_id: project ID or project number of the Cloud project your instance belongs to. zone: name of the zone your instance belongs to. instance_name: name of the instance you want to suspend. """instance_client=compute_v1.InstancesClient()operation=instance_client.suspend(project=project_id,zone=zone,instance=instance_name)wait_for_extended_operation(operation,"suspend instance")REST
To suspend an instance, make aPOST request to theinstances.suspend method:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspendReplace the following:
PROJECT_ID: the ID of the project where the instanceis located.ZONE: the zone where the instance is located.INSTANCE_NAME: the name of the instance.
Suspend an instance with Local SSD disks
Based on how many compute instances you want to suspend simultaneously andwhether you need to preserve the data of their attached Local SSD disks, do thefollowing:
To preserve the data of the Local SSD disks attached to an instance(excluding instances with Titanium SSD disks), suspend the instance using thegcloud CLI or REST API.
Caution: Compute Engine uses persistent storage to store your LocalSSD data. Before suspending an instance, ensure that you have enough quotafor the storage space used. Otherwise, suspending the instance fails. Formore information, seeStop or suspend a VM with Local SSD disks.To suspend multiple instances simultaneously, use the Google Cloud consoleor, for instances located in the same zone, the gcloud CLI.
To suspend one or more instances that have Local SSD disks attached, select oneof the following options:
Console
In the Google Cloud console, go to theVM instances page.
Select one or more instances to suspend.
ClickSuspend, and thenclickSuspend to confirm.
gcloud
When suspending one or more instances in a single zone that have Local SSDdisks attached, specify whether to discard or preserve Local SSD data asfollows:
To discard Local SSD data, use the
gcloud compute instances suspendcommandwith the--discard-local-ssd=trueflag:gcloud compute instances suspendINSTANCE_NAMES \ --discard-local-ssd=true \ --zone=ZONETo preserve Local SSD data, use the
gcloud beta compute instances suspendcommandwith the--discard-local-ssd=falseflag:Preview — The
--discard-local-ssd=falseflagThis 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 suspendINSTANCE_NAMES \ --discard-local-ssd=false \ --zone=ZONE
Replace the following:
INSTANCE_NAMES: a whitespace-separated list of namesof instances—for example,instance-01 instance-02 instance-03.ZONE: the zone where the instances are located.
REST
When suspending an instance that has Local SSD disks attached, specifywhether to discard or preserve Local SSD data as follows:
To discard Local SSD data, make a
POSTrequest to theinstances.suspendmethod.In the request URL, include thediscardLocalSsdquery parameter set totrue:POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend?discardLocalSsd=trueTo preserve Local SSD data, make a
POSTrequest to thebeta.instances.suspendmethod.In the request URL, include thediscardLocalSsdquery parameter set tofalse:Preview — The
discardLocalSsd=falsequery parameterThis 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.
POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend?discardLocalSsd=false
Replace the following:
PROJECT_ID: the ID of the project where the instanceis located.ZONE: the zone where the instance is located.INSTANCE_NAME: the name of the instance.
Resume a suspended instance
Before resuming a suspended compute instance, consider the following:
You can resume an instance only if there is sufficient capacity in the zonewhere the instance is located. This isn't usually a problem. If you havetroubles resuming an instance, then try again later.
If you attached Local SSD disks to the instance and chose to preserve LocalSSD data when suspending it, then you might need to remount the Local SSDdisks after resuming it. For more information, see how to remount non-bootdisks onLinux instances orWindows instances.
You can resume multiple instances simultaneously or individual instances. Formultiple instances, use the Google Cloud console or, for instances located inthe same zone, the gcloud CLI. For individual instances, select anyof the following options:
Console
In the Google Cloud console, go to theVM instances page.
Select one or more suspended instances to resume.
ClickStart / Resume,and then clickStart.
gcloud
To resume one or more suspended instances in a single zone, use thegcloud compute instances resume command:
gcloud compute instances resumeINSTANCE_NAMES \ --zone=ZONEReplace the following:
INSTANCE_NAMES: a whitespace-separated list of namesof instances—for example,instance-01 instance-02 instance-03.ZONE: the zone where the suspended instances arelocated.
Go
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb")// resumeInstance resumes a suspended Google Compute Engine instance// (with unencrypted disks).funcresumeInstance(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()getInstanceReq:=&computepb.GetInstanceRequest{Project:projectID,Zone:zone,Instance:instanceName,}instance,err:=instancesClient.Get(ctx,getInstanceReq)iferr!=nil{returnfmt.Errorf("unable to get instance: %w",err)}ifinstance.GetStatus()!="SUSPENDED"{returnfmt.Errorf("only suspended instances can be resumed, instance %s is in %s state",instanceName,instance.GetStatus(),)}resumeInstanceReq:=&computepb.ResumeInstanceRequest{Project:projectID,Zone:zone,Instance:instanceName,}op,err:=instancesClient.Resume(ctx,resumeInstanceReq)iferr!=nil{returnfmt.Errorf("unable to resume instance: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance resumed\n")returnnil}Java
importcom.google.cloud.compute.v1.Instance.Status;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;publicclassResumeInstance{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// project: project ID or project number of the Cloud project your instance belongs to.// zone: name of the zone your instance belongs to.// instanceName: name of the instance your want to resume.Stringproject="your-project-id";Stringzone="zone-name";StringinstanceName="instance-name";resumeInstance(project,zone,instanceName);}// Resume a suspended Google Compute Engine instance (with unencrypted disks).// Instance state changes to RUNNING, if successfully resumed.publicstaticvoidresumeInstance(Stringproject,Stringzone,StringinstanceName)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Instantiates a client.try(InstancesClientinstancesClient=InstancesClient.create()){StringcurrentInstanceState=instancesClient.get(project,zone,instanceName).getStatus();// Check if the instance is currently suspended.if(!currentInstanceState.equalsIgnoreCase(Status.SUSPENDED.toString())){thrownewRuntimeException(String.format("Only suspended instances can be resumed. Instance %s is in %s state.",instanceName,currentInstanceState));}Operationoperation=instancesClient.resumeAsync(project,zone,instanceName).get(300,TimeUnit.SECONDS);if(operation.hasError()||!instancesClient.get(project,zone,instanceName).getStatus().equalsIgnoreCase(Status.RUNNING.toString())){System.out.println("Cannot resume instance. Try again!");return;}System.out.printf("Instance resumed successfully ! %s",instanceName);}}}Node.js
/** * TODO(developer): Uncomment and replace 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');// Resumes a suspended Google Compute Engine instance (with unencrypted disks).asyncfunctionresumeInstance(){constinstancesClient=newcompute.InstancesClient();const[instance]=awaitinstancesClient.get({project:projectId,zone,instance:instanceName,});if(instance.status!=='SUSPENDED'){thrownewError('Only suspended instances can be resumed.'+`Instance${instanceName} is in${instance.status} state.`);}const[response]=awaitinstancesClient.resume({project:projectId,zone,instance:instanceName,});letoperation=response.latestResponse;constoperationsClient=newcompute.ZoneOperationsClient();// Wait for the create operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log('Instance resumed.');}resumeInstance();PHP
use Google\Cloud\Compute\V1\Client\InstancesClient;use Google\Cloud\Compute\V1\ResumeInstanceRequest;/** * Resume a suspended Google Compute Engine instance (with unencrypted disks). * * @param string $projectId Project ID or project number of the Cloud project your instance belongs to. * @param string $zone Name of the zone your instance belongs to. * @param string $instanceName Name of the instance you want to resume. * * @throws \Google\ApiCore\ApiException if the remote call fails. * @throws \Google\ApiCore\ValidationException if local error occurs before remote call. */function resume_instance( string $projectId, string $zone, string $instanceName) { // Resume the suspended Compute Engine instance using InstancesClient. $instancesClient = new InstancesClient(); $request = (new ResumeInstanceRequest()) ->setInstance($instanceName) ->setProject($projectId) ->setZone($zone); $operation = $instancesClient->resume($request); // Wait for the operation to complete. $operation->pollUntilComplete(); if ($operation->operationSucceeded()) { printf('Instance %s resumed successfully' . PHP_EOL, $instanceName); } else { $error = $operation->getError(); printf('Failed to resume 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)returnresultdefresume_instance(project_id:str,zone:str,instance_name:str)->None:""" Resume a suspended Google Compute Engine instance (with unencrypted disks). Args: project_id: project ID or project number of the Cloud project your instance belongs to. zone: name of the zone your instance belongs to. instance_name: name of the instance you want to resume. """instance_client=compute_v1.InstancesClient()instance=instance_client.get(project=project_id,zone=zone,instance=instance_name)ifinstance.status!=compute_v1.Instance.Status.SUSPENDED.name:raiseRuntimeError(f"Only suspended instances can be resumed. "f"Instance{instance_name} is in{instance.status} state.")operation=instance_client.resume(project=project_id,zone=zone,instance=instance_name)wait_for_extended_operation(operation,"instance resumption")REST
To resume a suspended instance, make aPOST request to theinstances.resume method:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/resumeReplace the following:
INSTANCE_NAME: the name of the suspend instance toresume.PROJECT_ID: the ID of the project where the suspendedinstance is located.ZONE: the zone where the suspended instance islocated.
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 2026-02-18 UTC.