暫停或恢復 Compute Engine 執行個體


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

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

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

  • 在非使用期間 (例如晚上或週末) 未完全使用的開發和測試環境,以及您想要保留的環境,以便節省成本或比建立新執行個體更快完成初始化。

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

事前準備

必要的角色

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

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

所需權限

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

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

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

限制

暫停運算執行個體時,會受到下列限制:

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

  • 您必須先設定作業系統,才能暫停使用 Debian 8 或 9 做為訪客作業系統的執行個體。

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

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

  • 您無法暫停搭載 GPU 的執行個體。

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

  • 您無法暫停機密 VM。

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

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

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

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

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

設定 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 中安裝 D-Bus,請在 OS 使用 Debian 8 或 9 時執行下列操作:

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

  2. 安裝 D-Bus:

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

    sudo systemctl restart systemd-logind.service
    

暫停執行個體

如果運算執行個體的來賓作業系統使用 Debian 8 或 9,則在暫停執行個體前,您必須設定來賓作業系統,以便支援暫停和繼續作業,如本文所述。

如要暫停執行個體,請根據執行個體是否已連結本機 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 磁碟的資料,請執行下列操作:

  • 如要保留已連結至執行個體 (不含 Z3 執行個體) 的本機 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 要求。在要求網址中加入設為 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:已暫停的執行個體所在的區域。

後續步驟