暫停或恢復 Compute Engine 執行個體


本文說明如何暫停或繼續執行 Compute Engine 執行個體。如要進一步瞭解如何暫停、停止或重設執行個體,請參閱「暫停、停止或重設 Compute Engine 執行個體」。

如果您想保留 Compute Engine 執行個體,但不想在執行個體閒置時產生費用,可以暫停執行個體。暫停執行個體時,系統會保留執行個體,並將執行個體記憶體的內容遷移至儲存空間。執行個體恢復運作後,Compute Engine 會將執行個體的記憶體從儲存空間遷移回執行個體,執行個體就會再次開始運作。

暫停 Compute Engine 執行個體有以下用途:

  • 在非工作時間 (例如晚上或週末) 未充分使用的開發和測試環境,但您想保留這些環境,以節省成本或加快初始化速度 (相較於建立新執行個體)。

  • 應用程式在執行個體完成啟動後,需要長時間初始化,但應用程式尚未準備好處理第一個要求,例如虛擬開發人員工作站或複雜的 Java 應用程式。

事前準備

  • 如果尚未設定驗證,請先完成設定。 「驗證」是指驗證身分的程序,確認您有權存取 Google Cloud 服務和 API。如要從本機開發環境執行程式碼或範例,請選取下列其中一個選項,向 Compute Engine 進行驗證:

    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

    1. After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    2. Set a default region and zone.
    3. Go

      如要在本機開發環境中使用本頁的 Go 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        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.

      5. 詳情請參閱 Set up authentication for a local development environment

      Java

      如要在本機開發環境中使用本頁的 Java 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        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.

      5. 詳情請參閱 Set up authentication for a local development environment

      Node.js

      如要在本機開發環境中使用本頁的 Node.js 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        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.

      5. 詳情請參閱 Set up authentication for a local development environment

      PHP

      如要在本機開發環境中使用本頁的 PHP 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        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.

      5. 詳情請參閱 Set up authentication for a local development environment

      Python

      如要在本機開發環境中使用本頁的 Python 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        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.

      5. 詳情請參閱 Set up authentication for a local development environment

      REST

      如要在本機開發環境中使用本頁的 REST API 範例,請使用您提供給 gcloud CLI 的憑證。

        After installing the Google Cloud CLI, initialize it by running the following command:

        gcloud init

        If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「Authenticate for using REST」。

必要的角色

如要取得暫停或恢復運算執行個體所需的權限,請要求管理員授予您執行個體的 Compute 執行個體管理員 (v1) (roles/compute.instanceAdmin.v1) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

這個預先定義的角色具備暫停或恢復運算執行個體所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要暫停或恢復運算執行個體,您必須具備下列權限:

  • 如何暫停執行個體: compute.instances.suspend
  • 如要繼續執行執行個體,請按照下列步驟操作: compute.instances.resume

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

限制

暫停運算執行個體時,須遵守下列限制:

  • 只有在客體 OS 支援暫停功能時,您才能暫停執行個體。詳情請參閱「作業系統詳細資料」。

  • 如果執行個體使用 Debian 8 或 9 做為客體 OS,您必須先設定 OS,才能暫停執行個體。

  • 您最多只能暫停執行個體 60 天,之後 Compute Engine 會自動將執行個體狀態轉換為 TERMINATED

  • 您可以暫停 Spot VM 或先占執行個體,但如果 Compute Engine 在暫停作業完成前先占執行個體,Compute Engine 會結束暫停作業並先占執行個體。

  • 已附加 GPU 的執行個體無法暫停。

  • 您無法暫停 Bare Metal 執行個體。

  • 機密 VM 無法暫停。

  • 您無法使用執行個體訪客環境內建的標準程序暫停執行個體。不支援 Ubuntu 16.04 以上版本的 systemctl suspend 等指令。如果呼叫,Compute Engine 會忽略客內信號。

  • 記憶體超過 208 GB 的執行個體無法暫停。

  • 您無法暫停已連結受 CSEK 保護磁碟的執行個體。

在 Debian 8 或 9 中啟用暫停作業

如果運算執行個體以 Debian 8 和 9 做為客體 OS 執行,則在暫停執行個體前,您必須執行下列其中一項操作,啟用暫停和恢復作業:

設定 ACPID

如要在 Debian 8 或 9 中啟用暫停和繼續作業,可以設定進階設定和電源介面事件 Daemon (ACPID),處理休眠按鈕事件。啟用深層休眠按鈕事件後,您可以新增殼層指令碼來處理休眠事件,詳情請參閱本節。

如要設定 ACPID 以支援暫停和繼續作業,請執行下列操作:

  1. 如果尚未連線,請連線至 Linux 執行個體

  2. acpi 資料夾中建立 events 資料夾:

    sudo mkdir -p /etc/acpi/events/
    
  3. 設定 ACPID 來處理睡眠按鈕事件:

    cat <<EOF | sudo tee /etc/acpi/events/sleepbtn-acpi-support
    event=button[ /]sleep
    action=/etc/acpi/sleepbtn-acpi-support.sh
    EOF
    
  4. 建立睡眠事件處理指令碼:

    cat <<EOF | sudo tee /etc/acpi/sleepbtn-acpi-support.sh
    #!/bin/sh
    echo mem > /sys/power/state
    EOF
    
  5. 設定指令碼的權限:

    sudo chmod 755 /etc/acpi/sleepbtn-acpi-support.sh
    
  6. 如要讓變更生效,請重新啟動 ACPID:

    sudo systemctl restart acpid.service
    

安裝 D-Bus

如要在 Debian 8 或 9 中啟用暫停和恢復作業,可以安裝 D-Bus

如果作業系統使用 Debian 8 或 9,請按照下列步驟在運算執行個體的客體 OS 中安裝 D-Bus:

  1. 如果尚未連線,請連線至 Linux 執行個體

  2. 安裝 D-Bus:

    sudo apt-get install dbus
    
  3. 如要讓變更生效,請重新啟動 logind

    sudo systemctl restart systemd-logind.service
    

暫停執行個體

如果運算執行個體的客體 OS 使用 Debian 8 或 9,您必須先設定客體 OS,支援暫停和繼續作業,才能暫停執行個體。相關說明請參閱本文。

如要暫停執行個體,請根據執行個體是否已連結本機 SSD 磁碟,使用下列方法:

暫停不含本機 SSD 磁碟的執行個體

您可以同時暫停多個運算執行個體,也可以暫停個別執行個體。如要處理多個執行個體,請使用 Google Cloud 控制台;如要處理位於同一區域的執行個體,請使用 Google Cloud CLI。如要選取個別執行個體,請選擇下列任一選項:

主控台

  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往 VM 執行個體

  2. 選取要暫停的一或多個執行個體。

  3. 依序點選「暫停」和「暫停」,確認暫停。

gcloud

如要暫停單一區域中的一或多個執行個體,請使用 gcloud compute instances suspend 指令

gcloud compute instances suspend INSTANCE_NAMES \
    --zone=ZONE

更改下列內容:

  • INSTANCE_NAMES:以空白字元分隔的執行個體名稱清單,例如 instance-01 instance-02 instance-03

  • ZONE:執行個體所在的區域。

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.
func suspendInstance(w io.Writer, projectID, zone, instanceName string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"

	ctx := context.Background()
	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

	req := &computepb.SuspendInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
	}

	op, err := instancesClient.Suspend(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to suspend instance: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Instance suspended\n")

	return nil
}

Java


import com.google.cloud.compute.v1.Instance.Status;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class SuspendInstance {

  public static void main(String[] args)
      throws IOException, 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.

    String project = "your-project-id";
    String zone = "zone-name";
    String instanceName = "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#limitations
  public static void suspendInstance(String project, String zone, String instanceName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Instantiates a client.
    try (InstancesClient instancesClient = InstancesClient.create()) {

      Operation operation = 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';

const compute = require('@google-cloud/compute');

// Suspends a running Google Compute Engine instance.
async function suspendInstance() {
  const instancesClient = new compute.InstancesClient();

  const [response] = await instancesClient.suspend({
    project: projectId,
    zone,
    instance: instanceName,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

  // Wait for the create operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.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__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_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)

    if operation.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)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def suspend_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

如要暫停執行個體,請對 instances.suspend 方法發出 POST 要求:

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

更改下列內容:

  • PROJECT_ID:執行個體所在專案的 ID。

  • ZONE:執行個體所在的區域。

  • INSTANCE_NAME:執行個體的名稱。

暫停具有本機 SSD 磁碟的執行個體

根據您要同時暫停的運算執行個體數量,以及是否需要保留所連本機 SSD 磁碟的資料,採取下列做法:

  • 如要保留附加至執行個體的本機 SSD 磁碟資料 (Z3 執行個體除外),請使用 gcloud CLI 或 REST API 暫停執行個體。

  • 如要同時暫停多個執行個體,請使用 Google Cloud 控制台,或針對位於相同區域的執行個體使用 gcloud CLI。

如要暫停一或多個已附加本機 SSD 磁碟的執行個體,請選取下列其中一個選項:

主控台

  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往 VM 執行個體

  2. 選取要暫停的一或多個執行個體。

  3. 依序點選「暫停」和「暫停」,確認暫停。

gcloud

如要暫停單一可用區中一或多個已連結本機 SSD 磁碟的執行個體,請指定是否要捨棄或保留本機 SSD 資料,方法如下:

  • 如要捨棄本機 SSD 資料,請使用 gcloud compute instances suspend 指令並加上 --discard-local-ssd=true 旗標:

    gcloud compute instances suspend INSTANCE_NAMES \
        --discard-local-ssd=true \
        --zone=ZONE
    
  • 如要保留本機 SSD 資料,請使用 gcloud beta compute instances suspend 指令並加上 --discard-local-ssd=false 標記:

    gcloud beta compute instances suspend INSTANCE_NAMES \
        --discard-local-ssd=false \
        --zone=ZONE
    

更改下列內容:

  • INSTANCE_NAMES:以空白字元分隔的執行個體名稱清單,例如 instance-01 instance-02 instance-03

  • ZONE:執行個體所在的區域。

REST

暫停已連結本機 SSD 磁碟的執行個體時,請指定是否要捨棄或保留本機 SSD 資料,方法如下:

  • 如要捨棄本機 SSD 資料,請對 instances.suspend 方法發出 POST 要求。在要求網址中,加入設為 truediscardLocalSsd 查詢參數:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend?discardLocalSsd=true
    
  • 如要保留本機 SSD 資料,請對 beta.instances.suspend 方法發出 POST 要求。在要求網址中,加入設為 falsediscardLocalSsd 查詢參數:

    POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend?discardLocalSsd=false
    

更改下列內容:

  • PROJECT_ID:執行個體所在專案的 ID。

  • ZONE:執行個體所在的區域。

  • INSTANCE_NAME:執行個體的名稱。

重新啟用暫停的執行個體

恢復遭停權的運算執行個體前,請先考量以下事項:

  • 只有在執行個體所在區域有足夠容量時,才能繼續執行個體。這通常不是問題。如果無法繼續使用執行個體,請稍後再試。

  • 如果您將本機 SSD 磁碟掛接到執行個體,並選擇在暫停執行個體時保留本機 SSD 資料,則可能需要在恢復執行個體後重新掛接本機 SSD 磁碟。詳情請參閱如何重新掛接 Linux 執行個體Windows 執行個體上的非開機磁碟。

您可以同時或個別恢復多個執行個體。如要刪除多個執行個體,請使用 Google Cloud 控制台,或針對位於同一區域的執行個體使用 gcloud CLI。如要個別選取執行個體,請選取下列任一選項:

主控台

  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往 VM 執行個體

  2. 選取要恢復的一或多個已暫停執行個體。

  3. 依序點選「啟動 / 繼續」和「啟動」

gcloud

如要重新啟用單一區域中一或多個已暫停的執行個體,請使用 gcloud compute instances resume 指令

gcloud compute instances resume INSTANCE_NAMES \
    --zone=ZONE

更改下列內容:

  • INSTANCE_NAMES:以空白字元分隔的執行個體名稱清單,例如 instance-01 instance-02 instance-03

  • ZONE:暫停執行個體所在的區域。

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).
func resumeInstance(w io.Writer, projectID, zone, instanceName string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"

	ctx := context.Background()
	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

	getInstanceReq := &computepb.GetInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
	}

	instance, err := instancesClient.Get(ctx, getInstanceReq)
	if err != nil {
		return fmt.Errorf("unable to get instance: %w", err)
	}

	if instance.GetStatus() != "SUSPENDED" {
		return fmt.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)
	if err != nil {
		return fmt.Errorf("unable to resume instance: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Instance resumed\n")

	return nil
}

Java


import com.google.cloud.compute.v1.Instance.Status;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ResumeInstance {

  public static void main(String[] args)
      throws IOException, 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.

    String project = "your-project-id";
    String zone = "zone-name";
    String instanceName = "instance-name";

    resumeInstance(project, zone, instanceName);
  }

  // Resume a suspended Google Compute Engine instance (with unencrypted disks).
  // Instance state changes to RUNNING, if successfully resumed.
  public static void resumeInstance(String project, String zone, String instanceName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Instantiates a client.
    try (InstancesClient instancesClient = InstancesClient.create()) {

      String currentInstanceState = instancesClient.get(project, zone, instanceName).getStatus();

      // Check if the instance is currently suspended.
      if (!currentInstanceState.equalsIgnoreCase(Status.SUSPENDED.toString())) {
        throw new RuntimeException(
            String.format("Only suspended instances can be resumed. Instance %s is in %s state.",
                instanceName, currentInstanceState));
      }

      Operation operation = 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';

const compute = require('@google-cloud/compute');

// Resumes a suspended Google Compute Engine instance (with unencrypted disks).
async function resumeInstance() {
  const instancesClient = new compute.InstancesClient();

  const [instance] = await instancesClient.get({
    project: projectId,
    zone,
    instance: instanceName,
  });

  if (instance.status !== 'SUSPENDED') {
    throw new Error(
      'Only suspended instances can be resumed.' +
        `Instance ${instanceName} is in ${instance.status} state.`
    );
  }

  const [response] = await instancesClient.resume({
    project: projectId,
    zone,
    instance: instanceName,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

  // Wait for the create operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.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__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_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)

    if operation.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)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def resume_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
    )
    if instance.status != compute_v1.Instance.Status.SUSPENDED.name:
        raise RuntimeError(
            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

如要重新啟用已暫停的執行個體,請對 instances.resume 方法發出 POST 要求:

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

更改下列內容:

  • INSTANCE_NAME:要恢復的暫停執行個體名稱。

  • PROJECT_ID:暫停執行個體所在的專案 ID。

  • ZONE:暫停執行個體所在的區域。

後續步驟