暫停或恢復 Compute Engine 執行個體

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

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

暫停 Compute Engine 執行個體有以下好處:

  • 在非尖峰時段 (例如晚上或週末) 未充分使用的開發和測試環境,且您希望維護這些環境,以節省成本或加快初始化速度,而非建立新的執行個體。

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

限制

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

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

  • 如要暫停使用下列 OS 映像檔的執行個體,您必須按照本文說明設定 OS:

    • Debian 8 或 9

    • 任何 Windows OS

  • 執行個體最多只能暫停 60 天,超過這個期限後,Compute Engine 會自動將狀態轉換為 TERMINATED。

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

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

  • 您無法暫停下列類型的執行個體:

    • Bare Metal 執行個體。

    • Confidential VM。

    • 已連結 GPU 或 TPU 的執行個體。

    • 記憶體超過 208 GB 的執行個體。

    • 已連結受 CSEK 保護 (已淘汰) 磁碟的執行個體。

事前準備

  • 確認專案在執行個體所在區域有足夠的 Persistent disk standard (GB) 配額。暫停執行個體時,Compute Engine 會將執行個體的記憶體儲存在永久儲存空間,這會耗用 Persistent disk standard (GB) 配額。這項規定適用於所有執行個體,包括僅連接 Google Cloud Hyperdisk 磁碟區的執行個體。詳情請參閱「磁碟配額」和「排解磁碟配額不足的問題」。
  • 如果尚未設定驗證,請先完成設定。驗證程序會確認您的身分,以便您存取 Google Cloud 服務和 API。如要從本機開發環境執行程式碼或範例,您可以選取下列其中一個選項,向 Compute Engine 進行驗證:

    請根據您打算如何使用本頁範例,選取對應的分頁標籤:

    控制台

    使用 Google Cloud 控制台存取 Google Cloud 服務和 API 時,您不需要設定驗證機制。

    gcloud

    1. 安裝 Google Cloud CLI,然後使用聯合身分登入 gcloud CLI。 登入後, 執行下列指令來初始化 Google Cloud CLI:

      gcloud init
  • 設定預設區域和可用區。
  • Go

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

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Java

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

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Node.js

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

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    PHP

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

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Python

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

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    REST

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

      安裝 Google Cloud CLI,然後使用聯合身分登入 gcloud CLI。

    詳情請參閱 Google Cloud 驗證說明文件中的「使用 REST 進行驗證」一節。

必要的角色

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

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

所需權限

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

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

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

啟用客體 OS 的暫停作業

如果運算執行個體使用 Debian 8 或 9 做為客體 OS,或使用任何 Windows OS,則必須先設定 OS,才能暫停及恢復執行個體。如果執行個體使用其他客體 OS,請略過本節。

在 Debian 8 或 9 啟用暫停作業

如要暫停或恢復使用 Debian 8 或 9 做為客體 OS 的運算執行個體,您必須先使用下列其中一種方法設定客體 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。

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

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

  2. 安裝 D-Bus:

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

    sudo systemctl restart systemd-logind.service
    

在 Windows 上啟用暫停作業

如要暫停使用 Windows 訪客 OS 的執行個體,必須在 OS 中停用休眠功能。如果您匯入 Windows 映像檔,系統可能會預設啟用休眠功能,您必須停用該功能,才能暫停執行個體。

如要在 Windows 中停用休眠功能,請按照下列步驟操作:

  1. 如果您尚未連線至 Windows 執行個體,請先連線。

  2. 以管理員身分開啟 PowerShell。

  3. 停用休眠模式:

    powercfg -h off
    
  4. 確認休眠功能已停用:

    powercfg -a
    

暫停執行個體

如果運算執行個體的客體 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./compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend

更改下列內容:

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

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

  • INSTANCE_NAME:執行個體的名稱。

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

根據您要同時暫停的運算執行個體數量,以及是否需要保留附加本機 SSD 磁碟的資料,請執行下列操作:

  • 如要保留附加至執行個體的本機 SSD 磁碟資料 (不含 Titanium SSD 磁碟),請使用 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 要求。在要求網址中,加入設為 true 的 discardLocalSsd 查詢參數:

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

    POST https://compute./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./compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/resume

更改下列內容:

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

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

  • ZONE:已暫停執行個體所在的可用區。

後續步驟