Compute Engine インスタンスを一時停止または再開する


このドキュメントでは、Compute Engine インスタンスを一時停止または再開する方法について説明します。インスタンスの一時停止、停止、リセットの詳細については、Compute Engine インスタンスを一時停止、停止、リセットするをご覧ください。

Compute Engine インスタンスを維持するが、使用していないときに課金されたくない場合は、インスタンスを一時停止できます。インスタンスを一時停止すると、インスタンスは保持され、インスタンスのメモリの内容がストレージに移行されます。インスタンスを再開すると、Compute Engine はインスタンスのメモリをストレージからインスタンスに戻し、インスタンスの実行を再開します。

Compute Engine インスタンスを一時停止すると、次のことができます。

  • 夜間や週末などのオフ時間に使用率が低い開発環境やテスト環境。新しいインスタンスを作成する場合よりもコストを抑え、短時間で初期化を行うために維持する必要がある環境です。

  • 仮想デベロッパー ワークステーションや複雑な Java アプリケーションなど、インスタンスの起動が完了してから最初のリクエストを処理するまでに初期化に時間がかかるアプリケーション。

始める前に

  • まだ設定していない場合は、認証を設定します。認証とは、 Google Cloud サービスと API にアクセスするために ID を確認するプロセスです。ローカル開発環境からコードまたはサンプルを実行するには、次のいずれかのオプションを選択して 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. Install the Google Cloud CLI, then initialize it by running the following command:

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

      ローカル開発環境でこのページの Go サンプルを使用するには、gcloud CLI をインストールして初期化し、ユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定します。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      詳細については Set up authentication for a local development environment をご覧ください。

      Java

      ローカル開発環境でこのページの Java サンプルを使用するには、gcloud CLI をインストールして初期化し、ユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定します。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      詳細については Set up authentication for a local development environment をご覧ください。

      Node.js

      ローカル開発環境でこのページの Node.js サンプルを使用するには、gcloud CLI をインストールして初期化し、ユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定します。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      詳細については Set up authentication for a local development environment をご覧ください。

      PHP

      ローカル開発環境でこのページの PHP サンプルを使用するには、gcloud CLI をインストールして初期化し、ユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定します。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      詳細については Set up authentication for a local development environment をご覧ください。

      Python

      ローカル開発環境でこのページの Python サンプルを使用するには、gcloud CLI をインストールして初期化し、ユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定します。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      詳細については Set up authentication for a local development environment をご覧ください。

      REST

      このページの REST API サンプルをローカル開発環境で使用するには、gcloud CLI に指定した認証情報を使用します。

        Install the Google Cloud CLI, then initialize it by running the following command:

        gcloud init

      詳細については、 Google Cloud 認証ドキュメントの REST を使用して認証するをご覧ください。

必要なロール

Compute インスタンスの一時停止と再開に必要な権限を取得するには、インスタンスに対する Compute インスタンス管理者(v1) roles/compute.instanceAdmin.v1)IAM ロールを付与するように管理者に依頼してください。ロールの付与については、プロジェクト、フォルダ、組織へのアクセス権の管理をご覧ください。

この事前定義ロールには、コンピューティング インスタンスの一時停止または再開に必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

コンピューティング インスタンスを一時停止または再開するには、次の権限が必要です。

  • インスタンスを一時停止する: compute.instances.suspend
  • インスタンスを再開する: compute.instances.resume

カスタムロールや他の事前定義ロールを使用して、これらの権限を取得することもできます。

制限事項

コンピューティング インスタンスを一時停止する場合は、次の制限が適用されます。

  • インスタンスを一時停止できるのは、ゲスト OS が一時停止をサポートしている場合のみです。詳しくは、オペレーティング システムの詳細をご覧ください。

  • ゲスト OS として Debian 8 または 9 を使用するインスタンスを一時停止できるのは、インスタンスを一時停止する前にOS を構成した場合のみです。

  • インスタンスを一時停止できる期間は最大 60 日です。この期間を経過すると、Compute Engine はインスタンスの状態を TERMINATED に自動的に移行します。

  • Spot VM とプリエンプティブル インスタンスを一時停止できますが、一時停止オペレーションが完了する前に Compute Engine がインスタンスをプリエンプトする場合、Compute Engine は一時停止オペレーションを終了してからインスタンスをプリエンプトします。

  • GPU がアタッチされているインスタンスは一時停止できません。

  • ベアメタル インスタンスは一時停止できません。

  • Confidential VM は一時停止できません。

  • ゲスト環境に組み込まれている標準プロセスを使用してインスタンスを一時停止することはできません。Ubuntu 16.04 以降の systemctl suspend などのコマンドはサポートされていません。呼び出されると、Compute Engine はゲスト内の信号を無視します。

  • メモリが 208 GB を超えるインスタンスは一時停止できません。

  • CSEK で保護されたディスクがアタッチされているインスタンスは一時停止できません。

Debian 8 または 9 で一時停止オペレーションを有効にする

コンピューティング インスタンスでゲスト OS として Debian 8 と 9 を実行している場合は、インスタンスを一時停止する前に、次のいずれかの方法で一時停止と再開のオペレーションを有効にしておく必要があります。

ACPID を構成する

Debian 8 または 9 で一時停止と再開のオペレーションを有効にするには、スリープボタン イベントを処理するように Advanced Configuration and Power Interface(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
    

インスタンスを一時停止する

コンピューティング インスタンスのゲスト OS が Debian 8 または 9 を使用している場合は、インスタンスを一時停止する前に、このドキュメントの説明に従い、停止オペレーションと再開オペレーションをサポートするようにゲスト OS を構成する必要があります。

インスタンスを一時停止するには、インスタンスにローカル SSD ディスクがアタッチされているかどうかに応じて、以下のいずれかの方法を使用します。

ローカル SSD ディスクがアタッチされていないインスタンスを一時停止する

複数のコンピューティング インスタンスを同時に一時停止することも、個々のインスタンスを一時停止することもできます。複数のインスタンスの場合は、Google Cloud コンソールを使用します。同じゾーンにあるインスタンスの場合は、Google Cloud CLI を使用します。個々のインスタンスの場合は、次のいずれかのオプションを選択します。

コンソール

  1. Google Cloud コンソールで [VM インスタンス] ページに移動します。

    [VM インスタンス] に移動

  2. 一時停止するインスタンスを 1 つ以上選択します。

  3. [一時停止] をクリックしてから、[一時停止] をクリックして確定します。

gcloud

1 つのゾーンで 1 つ以上のインスタンスを一時停止するには、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 つ以上のインスタンスを一時停止するには、次のいずれかのオプションを選択します。

コンソール

  1. Google Cloud コンソールで [VM インスタンス] ページに移動します。

    [VM インスタンス] に移動

  2. 一時停止するインスタンスを 1 つ以上選択します。

  3. [一時停止] をクリックしてから、[一時停止] をクリックして確定します。

gcloud

ローカル SSD ディスクがアタッチされている単一ゾーン内の 1 つ以上のインスタンスを一時停止する場合は、次のようにローカル SSD のデータを破棄するか保持するかを指定します。

  • ローカル SSD のデータを破棄するには、--discard-local-ssd=true フラグを指定して gcloud compute instances suspend コマンドを使用します。

    gcloud compute instances suspend INSTANCE_NAMES \
        --discard-local-ssd=true \
        --zone=ZONE
    
  • ローカル SSD のデータを保持するには、--discard-local-ssd=false フラグを指定して gcloud beta compute instances suspend コマンドを使用します。

    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 リクエストを送信します。リクエスト URL に、true に設定された discardLocalSsd クエリ パラメータを含めます。

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend?discardLocalSsd=true
    
  • ローカル SSD のデータを保持するには、beta.instances.suspend メソッドPOST リクエストを送信します。リクエスト URL に、false に設定された discardLocalSsd クエリ パラメータを含めます。

    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 インスタンス] ページに移動します。

    [VM インスタンス] に移動

  2. 再開する一時停止中のインスタンスを 1 つ以上選択します。

  3. [ 開始 / 再開]、[開始] の順にクリックします。

gcloud

1 つのゾーンで 1 つ以上の一時停止中のインスタンスを再開するには、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: 一時停止中のインスタンスが配置されているゾーン。

次のステップ