Stop or restart a Compute Engine instance Stay organized with collections Save and categorize content based on your preferences.
This document explains how to stop or restart a Compute Engine instance. Tolearn more about suspending, stopping, or resetting an instance, seeSuspend, stop, or reset Compute Engine instances.
Stopping an instance is useful when you no longer use it, or to modify itsproperties—for example, to change its machine type, or remove any attachedand mounted disks. After you stop the instance, you can do the following:
Restart it to resume your workload.
Delete it if you no longer need it.
To automate stopping or restarting an instance, see the following instead:
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 stop or restart 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 stop or restart a compute instance. To see the exact permissions that are required, expand theRequired permissions section:
Required permissions
The following permissions are required to stop or restart a compute instance:
- To stop an instance:
compute.instances.stopon the instance - To stop an instance from the guest OS:
compute.instances.setMetadataon the instance if it usesinstance-level public SSH keys. - To restart an instance:
compute.instances.starton the instance - To restart an instance that uses encryption keys:
compute.instances.startWithEncryptionKeyon the instance
You might also be able to get these permissions withcustom roles or otherpredefined roles.
Stop an instance
When you stop a compute instance, or Compute Engine does so for ascheduled action, the instance retains its attached resources, configurationsettings, internal IP addresses, MAC addresses, and metadata. However, theinstance loses its in-memory data and application state. If you need to retainthese states, thensuspend the instance instead.
Important: You keep incurring charges for any resources attached to a stoppedinstance. To avoid unnecessary costs, detach and delete any resources that youno longer need.You can stop an instance using the following methods, depending on whether theinstance has Local SSD disks attached and how you want to handle anyshutdown scripts:
Stop an instance without Local SSD disks
You can stop one or more instances simultaneously that don't have any LocalSSD disks attached. Any shutdown scripts in an instance must finish runningwithin the default shutdown period.
Stop an instance with Local SSD disks
When stopping one or more instances simultaneously that have Local SSD disksattached, you can choose to discard or preserve(Preview) the data on those disks. Anyshutdown scripts in the instance must finish running within the defaultshutdown period.
Stop an instance from the guest OS
This approach lets you stop a single instance only after your shutdownscripts have finished running, or, if you enabledgraceful shutdown,stop the instance without gracefully shutting it down, or end an ongoinggraceful shutdown. Unless you manually back up data from any attached LocalSSD disks to durable storage volume, stopping an instance from within itsguest OS discards any data on those disks.
Stop an instance without Local SSD disks
Depending on what you want to do when stopping an instance, use the followingoptions:
If you've enabled graceful shutdown in the instance, then you canstop the instance without gracefully shutting it down or end an ongoinggraceful shutdown using the Google Cloud console, gcloud CLI, orREST API.
To stop multiple instances simultaneously, use the Google Cloud consoleor, for instances located in the same zone, the gcloud CLI.
To stop one or more instances, select one of the following options:
Console
In the Google Cloud console, go to theVM instances page.
Select the running instances to stop.
ClickStop. If there isnoStop option, clickMore actions >Stop.
In the dialog, do the following:
Optional: To stop the instances without gracefully shut them down,or end an ongoing graceful shutdown, select theSkip graceful shutdown (if applicable) checkbox.
To confirm, clickStop.
gcloud
To stop one or more instances in the same zone, use thegcloud compute instances stop command:
gcloud compute instances stopINSTANCE_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, if you've enabled graceful shutdown in one or more instances,then you can stop the instances without gracefully shutting them down, ormanually end an ongoing graceful shutdown. To do so, use thegcloud beta compute instances stop commandwith the--no-graceful-shutdown flag:
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.--no-graceful-shutdown flag
gcloud beta compute instances stopINSTANCE_NAMES \--no-graceful-shutdown \ --zone=ZONEGo
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb")// stopInstance stops a started Google Compute Engine instancefuncstopInstance(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.StopInstanceRequest{Project:projectID,Zone:zone,Instance:instanceName,}op,err:=instancesClient.Stop(ctx,req)iferr!=nil{returnfmt.Errorf("unable to stop instance: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance stopped\n")returnnil}Java
importcom.google.api.gax.longrunning.OperationFuture;importcom.google.cloud.compute.v1.InstancesClient;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.Operation.Status;importcom.google.cloud.compute.v1.StopInstanceRequest;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassStopInstance{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 stop. */Stringproject="your-project-id";Stringzone="zone-name";StringinstanceName="instance-name";stopInstance(project,zone,instanceName);}// Stops a started Google Compute Engine instance.publicstaticvoidstopInstance(Stringproject,Stringzone,StringinstanceName)throwsIOException,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 `instancesClient.close()` method on the client to safely clean up any remaining background resources. */try(InstancesClientinstancesClient=InstancesClient.create()){StopInstanceRequeststopInstanceRequest=StopInstanceRequest.newBuilder().setProject(project).setZone(zone).setInstance(instanceName).build();OperationFuture<Operation,Operation>operation=instancesClient.stopAsync(stopInstanceRequest);Operationresponse=operation.get(3,TimeUnit.MINUTES);if(response.getStatus()==Status.DONE){System.out.println("Instance stopped successfully ! ");}}}}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');asyncfunctionstopInstance(){constinstancesClient=newcompute.InstancesClient();const[response]=awaitinstancesClient.stop({project:projectId,zone,instance:instanceName,});letoperation=response.latestResponse;constoperationsClient=newcompute.ZoneOperationsClient();// Wait for the operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log('Instance stopped.');}stopInstance();PHP
use Google\Cloud\Compute\V1\Client\InstancesClient;use Google\Cloud\Compute\V1\StopInstanceRequest;/** * Stops 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 stop. * * @throws \Google\ApiCore\ApiException if the remote call fails. * @throws \Google\ApiCore\ValidationException if local error occurs before remote call. */function stop_instance( string $projectId, string $zone, string $instanceName) { // Stop the Compute Engine instance using InstancesClient. $instancesClient = new InstancesClient(); $request = (new StopInstanceRequest()) ->setInstance($instanceName) ->setProject($projectId) ->setZone($zone); $operation = $instancesClient->stop($request); // Wait for the operation to complete. $operation->pollUntilComplete(); if ($operation->operationSucceeded()) { printf('Instance %s stopped successfully' . PHP_EOL, $instanceName); } else { $error = $operation->getError(); printf('Failed to stop 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)returnresultdefstop_instance(project_id:str,zone:str,instance_name:str)->None:""" Stops 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 your want to stop. """instance_client=compute_v1.InstancesClient()operation=instance_client.stop(project=project_id,zone=zone,instance=instance_name)wait_for_extended_operation(operation,"instance stopping")REST
To stop an instance, make aPOST request to theinstances.stop method:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/stopReplace the following:
INSTANCE_NAME: the name of the instance.PROJECT_ID: the ID of the project where the instanceis located.ZONE: the zone where the instance is located.
Optionally, if you've enabled graceful shutdown in an instance, you can stopthe instance without gracefully shutting it down, or manually end an ongoinggraceful shutdown. To do so, make aPOST request to theinstances.stop method.In the request URL, include thenoGracefulShutdown=true query parameter:
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
POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/stop?noGracefulShutdown=trueStop an instance with Local SSD disks
Depending on what you want to do when stopping a compute instance, use thefollowing options:
If you've enabled graceful shutdown in the instance, then you canstop the instance without gracefully shutting it down or end an ongoinggraceful shutdown using the Google Cloud console, gcloud CLI,or REST API.
To preserve the data of the Local SSD disks attached to an instance(excludingmachine types that use Titanium SSD),stop the instance using the gcloud CLIor REST API.
Caution: If you opt to preserve the Local SSD data, thenCompute Engine stores the Local SSD data on durable storage whilethe instance is stopped. Thus, before stopping the instance, ensure that youhave enough disk quota to store the Local SSD data.To stop multiple instances simultaneously, use the Google Cloud consoleor, for instances located in the same zone, the gcloud CLI.
To stop one or more instances that have Local SSD disks attached, select one ofthe following options:
Console
In the Google Cloud console, go to theVM instances page.
Select the running instances to stop.
ClickStop. If there isnoStop option, clickMore actions >Stop.
In the dialog, do the following:
Optional: To stop the instances without gracefully shut them down,or end an ongoing graceful shutdown, select theSkip graceful shutdown (if applicable) checkbox.
To confirm, clickStop.
gcloud
When stopping one or more instances in the same 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 stopcommandwith the--discard-local-ssd=trueflag:gcloud compute instances stopINSTANCE_NAMES \ --discard-local-ssd=true \ --zone=ZONETo preserve Local SSD data, use the
gcloud beta compute instances stopcommandwith 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 stopINSTANCE_NAMES \ --discard-local-ssd=false \ --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, if you've enabled graceful shutdown in one or more instances,you can stop the instances without gracefully shutting them down, or end anongoing graceful shutdown. To do so, use thegcloud beta compute instances stop commandwith the--no-graceful-shutdown flag:
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.--no-graceful-shutdown flag
gcloud beta compute instances stopINSTANCE_NAMES \ --discard-local-ssd=DISCARD_LOCAL_SSD \--no-graceful-shutdown \ --zone=ZONEReplaceDISCARD_LOCAL_SSD withtrue to discard the datain the Local SSD disks, orfalse to preserve the data.
REST
When stopping an instance that has Local SSD disks attached, specify whetherto discard or preserve Local SSD data as follows:
To discard Local SSD data, make a
POSTrequest to theinstances.stopmethod.In the request URL, include thediscardLocalSsdquery parameter set totrue:POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/stop?discardLocalSsd=trueTo preserve Local SSD data, make a
POSTrequest to thebeta.instances.stopmethod.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/stop?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.
Optionally, if you've enabled graceful shutdown in an instance, then you canstop the instance without gracefully shutting it down, or manually end anongoing graceful shutdown. To do so, make aPOST request to theinstances.stop method.In the request URL, include thenoGracefulShutdown=true query parameter:
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
POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/stop?discardLocalSsd=DISCARD_LOCAL_SSD&noGracefulShutdown=trueReplaceDISCARD_LOCAL_SSD withtrue to discard the datain the Local SSD disks, orfalse to preserve the data.
Stop an instance from the guest OS
If a compute instance has Local SSD disks attached, then shutting down the guestOS automatically discards the Local SSD data. To preserve this data, manuallycopy the data to a persistent storage option before stopping the instance.
To stop an instance from the guest OS, select one of the following options:
Linux
If you haven't already, thenconnect to the instance.
To stop the instance, select one of the following methods:
For a clean shutdown that allows the instance to run shutdownscripts before shutting down the guest OS, run the followingcommand:
sudo shutdown -h nowOtherwise, to force a shutdown, run the following command:
sudo poweroff
Windows
If you haven't already, then connect to the instance using one of thefollowing methods:
To stop the instance, select one of the following methods:
To cleanly stop the instance and let the instance to run shutdownscripts before shutting down the guest OS, run the followingcommand:
shutdown /sTo force a shutdown, run the following command:
shutdown /f
Restart an instance
You can restart a compute instance that has been fully stopped, which is whenthe instance state isTERMINATED.
If you chose to preserve the data of your Local SSD disks when stopping theinstance, then you might need to remount the Local SSD disks after restartingit. For more information about how to mount Local SSD disks, seeFormat and mounting a Local SSD device.
To restart an instance, use one of the following methods based on whether theinstance has encrypted disks attached:
If your instance doesn't have encrypted disks attached, then seeRestart an instance without encrypted disks.
Otherwise, seeRestart an instance with encrypted disks.
Restart an instance without encrypted disks
To restart multiple instances simultaneously across different zones, use theGoogle Cloud console. For instances located within the same zone, you can usethe gcloud CLI. Otherwise, for other restart scenarios, select one ofthe following options:
Console
In the Google Cloud console, go to theVM instances page.
Select one or more instances.
ClickStart / Resume.
gcloud
To restart one or more instances in the same zone, use thegcloud compute instances start command:
gcloud compute instances startINSTANCE_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.
Go
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb")// startInstance starts a stopped Google Compute Engine instance (with unencrypted disks).funcstartInstance(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.StartInstanceRequest{Project:projectID,Zone:zone,Instance:instanceName,}op,err:=instancesClient.Start(ctx,req)iferr!=nil{returnfmt.Errorf("unable to start instance: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance started\n")returnnil}Java
importcom.google.api.gax.longrunning.OperationFuture;importcom.google.cloud.compute.v1.InstancesClient;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.Operation.Status;importcom.google.cloud.compute.v1.StartInstanceRequest;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassStartInstance{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 start. */Stringproject="your-project-id";Stringzone="zone-name";StringinstanceName="instance-name";startInstance(project,zone,instanceName);}// Starts a stopped Google Compute Engine instance (with unencrypted disks).publicstaticvoidstartInstance(Stringproject,Stringzone,StringinstanceName)throwsIOException,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 `instancesClient.close()` method on the client to safely clean up any remaining background resources. */try(InstancesClientinstancesClient=InstancesClient.create()){// Create the request.StartInstanceRequeststartInstanceRequest=StartInstanceRequest.newBuilder().setProject(project).setZone(zone).setInstance(instanceName).build();OperationFuture<Operation,Operation>operation=instancesClient.startAsync(startInstanceRequest);// Wait for the operation to complete.Operationresponse=operation.get(3,TimeUnit.MINUTES);if(response.getStatus()==Status.DONE){System.out.println("Instance started successfully ! ");}}}}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');asyncfunctionstartInstance(){constinstancesClient=newcompute.InstancesClient();const[response]=awaitinstancesClient.start({project:projectId,zone,instance:instanceName,});letoperation=response.latestResponse;constoperationsClient=newcompute.ZoneOperationsClient();// Wait for the operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log('Instance started.');}startInstance();PHP
use Google\Cloud\Compute\V1\Client\InstancesClient;use Google\Cloud\Compute\V1\StartInstanceRequest;/** * Starts a stopped 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 stop. * * @throws \Google\ApiCore\ApiException if the remote call fails. * @throws \Google\ApiCore\ValidationException if local error occurs before remote call. */function start_instance( string $projectId, string $zone, string $instanceName) { // Start the Compute Engine instance using InstancesClient. $instancesClient = new InstancesClient(); $request = (new StartInstanceRequest()) ->setInstance($instanceName) ->setProject($projectId) ->setZone($zone); $operation = $instancesClient->start($request); // Wait for the operation to complete. $operation->pollUntilComplete(); if ($operation->operationSucceeded()) { printf('Instance %s started successfully' . PHP_EOL, $instanceName); } else { $error = $operation->getError(); printf('Failed to start 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)returnresultdefstart_instance(project_id:str,zone:str,instance_name:str)->None:""" Starts a stopped 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 your want to start. """instance_client=compute_v1.InstancesClient()operation=instance_client.start(project=project_id,zone=zone,instance=instance_name)wait_for_extended_operation(operation,"instance start")REST
To restart an instance, make aPOST request to theinstances.start method:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/startReplace the following:
INSTANCE_NAME: the name of the instance to restart.PROJECT_ID: the ID of the project where the instanceis located.ZONE: the zone where the instance is located.
Restart an instance with encrypted disks
When you restart a stopped compute instance that has attached disks that wereencrypted usingcustomer-supplied encryption keys,you must supply the encryption key information.
To restart multiple instances simultaneously across different zones, use theGoogle Cloud console. For instances located within the same zone, you can usethe gcloud CLI. Otherwise, for other restart scenarios, select one ofthe following options:
Console
In the Google Cloud console, go to theVM instances page.
Select the instances to restart.
ClickStart / Resume.
Specify encryption keys for each of the encrypted disks that areattached to the instances, and then clickStart.
gcloud
To restart one or more instances that use encrypted disks in the same zone,use thegcloud compute instances start commandwith the--csek-key-file flag. If you're using an RSA-wrapped key, thenuse thegcloud beta compute instances start commandwith the--csek-key-file flag instead:
gcloud compute instances startINSTANCE_NAMES \ --csek-key-file=ENCRYPTION_KEY_FILE \ --zone=ZONEReplace the following:
INSTANCE_NAMES: a list of instance names separated byspaces—for example,instance-01 instance-02 instance-03.ENCRYPTION_KEY_FILE: the relative path to the JSONfile that contains the customer-supplied encryption key. You can onlyrestart multiple instances simultaneously if the instances use the samecustomer-supplied encryption key.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""google.golang.org/protobuf/proto")// startInstanceWithEncKey starts a stopped Google Compute Engine instance (with encrypted disks).funcstartInstanceWithEncKey(wio.Writer,projectID,zone,instanceName,keystring)error{// projectID := "your_project_id"// zone := "europe-central2-b"// instanceName := "your_instance_name"// key := "your_encryption_key"ctx:=context.Background()instancesClient,err:=compute.NewInstancesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewInstancesRESTClient: %w",err)}deferinstancesClient.Close()instanceReq:=&computepb.GetInstanceRequest{Project:projectID,Zone:zone,Instance:instanceName,}instance,err:=instancesClient.Get(ctx,instanceReq)iferr!=nil{returnfmt.Errorf("unable to get instance: %w",err)}req:=&computepb.StartWithEncryptionKeyInstanceRequest{Project:projectID,Zone:zone,Instance:instanceName,InstancesStartWithEncryptionKeyRequestResource:&computepb.InstancesStartWithEncryptionKeyRequest{Disks:[]*computepb.CustomerEncryptionKeyProtectedDisk{{Source:proto.String(instance.GetDisks()[0].GetSource()),DiskEncryptionKey:&computepb.CustomerEncryptionKey{RawKey:proto.String(key),},},},},}op,err:=instancesClient.StartWithEncryptionKey(ctx,req)iferr!=nil{returnfmt.Errorf("unable to start instance with encryption key: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance with encryption key started\n")returnnil}Java
importcom.google.api.gax.longrunning.OperationFuture;importcom.google.cloud.compute.v1.CustomerEncryptionKey;importcom.google.cloud.compute.v1.CustomerEncryptionKeyProtectedDisk;importcom.google.cloud.compute.v1.GetInstanceRequest;importcom.google.cloud.compute.v1.Instance;importcom.google.cloud.compute.v1.InstancesClient;importcom.google.cloud.compute.v1.InstancesStartWithEncryptionKeyRequest;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.Operation.Status;importcom.google.cloud.compute.v1.StartWithEncryptionKeyInstanceRequest;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassStartEncryptedInstance{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 start. key: bytes object representing a raw base64 encoded key to your machines boot disk. For more information about disk encryption see: https://cloud.google.com/compute/docs/disks/customer-supplied-encryption#specifications */Stringproject="your-project-id";Stringzone="zone-name";StringinstanceName="instance-name";Stringkey="raw-key";startEncryptedInstance(project,zone,instanceName,key);}// Starts a stopped Google Compute Engine instance (with encrypted disks).publicstaticvoidstartEncryptedInstance(Stringproject,Stringzone,StringinstanceName,Stringkey)throwsIOException,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 `instancesClient.close()` method on the client to safely clean up any remaining background resources. */try(InstancesClientinstancesClient=InstancesClient.create()){GetInstanceRequestgetInstanceRequest=GetInstanceRequest.newBuilder().setProject(project).setZone(zone).setInstance(instanceName).build();Instanceinstance=instancesClient.get(getInstanceRequest);// Prepare the information about disk encryption.CustomerEncryptionKeyProtectedDiskprotectedDisk=CustomerEncryptionKeyProtectedDisk.newBuilder()/* Use raw_key to send over the key to unlock the disk To use a key stored in KMS, you need to provide: `kms_key_name` and `kms_key_service_account` */.setDiskEncryptionKey(CustomerEncryptionKey.newBuilder().setRawKey(key).build()).setSource(instance.getDisks(0).getSource()).build();InstancesStartWithEncryptionKeyRequeststartWithEncryptionKeyRequest=InstancesStartWithEncryptionKeyRequest.newBuilder().addDisks(protectedDisk).build();StartWithEncryptionKeyInstanceRequestencryptionKeyInstanceRequest=StartWithEncryptionKeyInstanceRequest.newBuilder().setProject(project).setZone(zone).setInstance(instanceName).setInstancesStartWithEncryptionKeyRequestResource(startWithEncryptionKeyRequest).build();OperationFuture<Operation,Operation>operation=instancesClient.startWithEncryptionKeyAsync(encryptionKeyInstanceRequest);Operationresponse=operation.get(3,TimeUnit.MINUTES);if(response.getStatus()==Status.DONE){System.out.println("Encrypted instance started successfully ! ");}}}}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'// const key = 'YOUR_KEY_STRING'constcompute=require('@google-cloud/compute');asyncfunctionstartInstanceWithEncryptionKey(){constinstancesClient=newcompute.InstancesClient();const[instance]=awaitinstancesClient.get({project:projectId,zone,instance:instanceName,});const[response]=awaitinstancesClient.startWithEncryptionKey({project:projectId,zone,instance:instanceName,instancesStartWithEncryptionKeyRequestResource:{disks:[{source:instance.disks[0].source,diskEncryptionKey:{rawKey:key,},},],},});letoperation=response.latestResponse;constoperationsClient=newcompute.ZoneOperationsClient();// Wait for the operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log('Instance with encryption key started.');}startInstanceWithEncryptionKey();PHP
use Google\Cloud\Compute\V1\Client\InstancesClient;use Google\Cloud\Compute\V1\CustomerEncryptionKey;use Google\Cloud\Compute\V1\CustomerEncryptionKeyProtectedDisk;use Google\Cloud\Compute\V1\GetInstanceRequest;use Google\Cloud\Compute\V1\InstancesStartWithEncryptionKeyRequest;use Google\Cloud\Compute\V1\StartWithEncryptionKeyInstanceRequest;/** * Starts a stopped Google Compute Engine instance (with encrypted 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 stop. * @param string $key Bytes object representing a raw base64 encoded key to your instance's boot disk. * For more information about disk encryption see: * https://cloud.google.com/compute/docs/disks/customer-supplied-encryption#specifications * * @throws \Google\ApiCore\ApiException if the remote call fails. * @throws \Google\ApiCore\ValidationException if local error occurs before remote call. */function start_instance_with_encryption_key( string $projectId, string $zone, string $instanceName, string $key) { // Initiate the InstancesClient. $instancesClient = new InstancesClient(); // Get data about the instance. $request = (new GetInstanceRequest()) ->setInstance($instanceName) ->setProject($projectId) ->setZone($zone); $instanceData = $instancesClient->get($request); // Use `setRawKey` to send over the key to unlock the disk // To use a key stored in KMS, you need to use `setKmsKeyName` and `setKmsKeyServiceAccount` $customerEncryptionKey = (new CustomerEncryptionKey()) ->setRawKey($key); /** @var \Google\Cloud\Compute\V1\AttachedDisk */ $disk = $instanceData->getDisks()[0]; // Prepare the information about disk encryption. $diskData = (new CustomerEncryptionKeyProtectedDisk()) ->setSource($disk->getSource()) ->setDiskEncryptionKey($customerEncryptionKey); // Set request with one disk. $instancesStartWithEncryptionKeyRequest = (new InstancesStartWithEncryptionKeyRequest()) ->setDisks(array($diskData)); // Start the instance with encrypted disk. $request2 = (new StartWithEncryptionKeyInstanceRequest()) ->setInstance($instanceName) ->setInstancesStartWithEncryptionKeyRequestResource($instancesStartWithEncryptionKeyRequest) ->setProject($projectId) ->setZone($zone); $operation = $instancesClient->startWithEncryptionKey($request2); // Wait for the operation to complete. $operation->pollUntilComplete(); if ($operation->operationSucceeded()) { printf('Instance %s started successfully' . PHP_EOL, $instanceName); } else { $error = $operation->getError(); printf('Starting instance failed: %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)returnresultdefstart_instance_with_encryption_key(project_id:str,zone:str,instance_name:str,key:bytes)->None:""" Starts a stopped Google Compute Engine instance (with encrypted 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 your want to start. key: bytes object representing a raw base64 encoded key to your machines boot disk. For more information about disk encryption see: https://cloud.google.com/compute/docs/disks/customer-supplied-encryption#specifications """instance_client=compute_v1.InstancesClient()instance_data=instance_client.get(project=project_id,zone=zone,instance=instance_name)# Prepare the information about disk encryptiondisk_data=compute_v1.CustomerEncryptionKeyProtectedDisk()disk_data.source=instance_data.disks[0].sourcedisk_data.disk_encryption_key=compute_v1.CustomerEncryptionKey()# Use raw_key to send over the key to unlock the disk# To use a key stored in KMS, you need to provide `kms_key_name` and `kms_key_service_account`disk_data.disk_encryption_key.raw_key=keyenc_data=compute_v1.InstancesStartWithEncryptionKeyRequest()enc_data.disks=[disk_data]operation=instance_client.start_with_encryption_key(project=project_id,zone=zone,instance=instance_name,instances_start_with_encryption_key_request_resource=enc_data,)wait_for_extended_operation(operation,"instance start (with encrypted disk)")REST
To restart an instance that uses encrypted disks, make aPOST request totheinstances.startWithEncryptionKey method:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/startWithEncryptionKey{ "disks": [ { "source": "DISK_URL", "diskEncryptionKey": { "ENCRYPTION_TYPE": "ENCRYPTION_KEY" } } ]}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.DISK_URL: theresource URLcorresponding to the full resource name of the attached disk that isencrypted with a customer-supplied encryption key.ENCRYPTION_TYPE: the type of disk encryption thatyou're using, which can be one of the following:rawKey,kmsKeyName,orrsaEncryptedKey. If you use thersaEncryptedKeytype, then make aPOSTrequest to thebeta.instances.startWithEncryptionKeymethod.ENCRYPTION_KEY: the encryption key used to encryptthe persistent disks attached to the instance.rawKeyorrsaEncryptedKeykeys must bebase64-encoded.Additionally, to prepare arsaEncryptedKeykey, seeRSA key wrapping.
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.