VM 일시정지 및 재개


이·문서에서는·가상·머신(VM) 인스턴스를 일시정지·및 재개하는 방법을 설명합니다. 인스턴스를 중지 및 시작하는 방법에 대한 자세한 내용은 인스턴스 중지 및 시작을 참조하세요. 인스턴스 수명 주기에 대한 자세한 내용은 인스턴스 수명주기 문서를 참조하세요.

VM 인스턴스를 유지하려고 하지만 사용하지 않을 때 비용이 청구되지 않게 하려면 VM을 정지하면 됩니다. VM을 정지하면 Google에서 프로젝트에 VM을 보존하고 VM 메모리 콘텐츠를 스토리지로 이전합니다. VM이 정지된 동안 Google은 VM 메모리를 보존하는 데 사용되는 스토리지에 대한 비용만 청구합니다. VM을 재개할 때 네트워크 함수가 예상대로 작동하도록 고정 IP 주소와 같은 속성은 그대로 유지됩니다. 재개 후 Google은 VM 메모리를 스토리지에서 인스턴스로 다시 이전하고 현재 실행 중인 VM 인스턴스에 대한 요금을 청구합니다.

다음과 같은 경우 인스턴스를 일시정지하는 것이 좋습니다.

  • VM 인스턴스를 새로 만드는 것보다 비용을 절감하거나 더 빠르게 초기화하기 위해 저녁이나 주말과 같은 비사용 기간 동안 완전히 활용되지 않는 개발 및 테스트 환경
  • 인스턴스의 부팅이 완료된 후 애플리케이션이 첫 번째 요청(예: 가상 개발자 워크스테이션 또는 복잡한 자바 애플리케이션)을 처리할 준비가 되기 전에 긴 초기화 기간이 필요한 애플리케이션

정지 작동 방식

인스턴스를 일시정지하면 ACPI S3 일시정지 신호를 인스턴스 운영체제에 전송합니다. 인스턴스 일시정지는 노트북 덮개를 닫는 것과 비슷하게 인스턴스를 SUSPENDED 상태로 전환하는 것입니다.

인스턴스 일시정지와 인스턴스 중지의 차이점은 다음과 같습니다.

인스턴스에 연결된 모든 리소스는 인스턴스에 연결된 상태로 유지되며 영구 디스크 및 고정 또는 예약된 외부 IP 주소를 포함하여 요금이 청구됩니다. 이러한 모든 리소스는 인스턴스가 정지된 경우에도 가격표에 따라 요금이 청구됩니다.

게스트 환경에 내장된 표준 프로세스를 사용하여 인스턴스를 정지할 수 없습니다. Ubuntu 16.04 이상의 systemctl suspend 명령어와 같은 명령어는 사용할 수 없습니다. Google Cloud CLI 또는 REST만 사용해서 인스턴스를 일시중지할 수 있습니다.

나중에 인스턴스를 재개할 때 인스턴스의 메모리와 기기 상태를 복원할 필요가 없는 경우 인스턴스를 중지할 수 있으며 추가 스토리지 요금이 발생하지 않습니다.

시작하기 전에

  • 아직 인증을 설정하지 않았다면 설정합니다. 인증은 Google Cloud 서비스 및 API에 액세스하기 위해 ID를 확인하는 프로세스입니다. 로컬 개발 환경에서 코드 또는 샘플을 실행하려면 다음과 같이 Compute Engine에 인증하면 됩니다.

    이 페이지의 샘플 사용 방법에 대한 탭을 선택하세요.

    콘솔

    Google Cloud 콘솔을 사용하여 Google Cloud 서비스 및 API에 액세스할 때는 인증을 설정할 필요가 없습니다.

    gcloud

    1. Google Cloud CLI를 설치한 후 다음 명령어를 실행하여 초기화합니다.

      gcloud init
    2. 기본 리전 및 영역을 설정합니다.

    Go

    로컬 개발 환경에서 이 페이지의 Go 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 로컬 개발 환경의 인증 설정를 참조하세요.

    Java

    로컬 개발 환경에서 이 페이지의 Java 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 로컬 개발 환경의 인증 설정를 참조하세요.

    Node.js

    로컬 개발 환경에서 이 페이지의 Node.js 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 로컬 개발 환경의 인증 설정를 참조하세요.

    PHP

    로컬 개발 환경에서 이 페이지의 PHP 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 로컬 개발 환경의 인증 설정를 참조하세요.

    Python

    로컬 개발 환경에서 이 페이지의 Python 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 로컬 개발 환경의 인증 설정를 참조하세요.

    REST

    로컬 개발 환경에서 이 페이지의 REST API 샘플을 사용하려면 gcloud CLI에 제공한 사용자 인증 정보를 사용합니다.

      Google Cloud CLI를 설치한 후 다음 명령어를 실행하여 초기화합니다.

      gcloud init

제한사항

이 기능에는 다음 제한사항이 적용됩니다.

  • GPU를 사용하는 인스턴스는 정지할 수 없습니다.
  • 게스트 환경에 내장된 표준 프로세스를 사용하여 인스턴스를 정지할 수 없습니다. Ubuntu 16.04 이상의 systemctl suspend 명령어와 같은 명령어는 사용할 수 없습니다. 게스트 내 신호는 무시됩니다.
  • VM이 자동으로 중지되기 전 최대 60일 동안만 인스턴스를 일시정지할 수 있습니다.
  • 메모리가 208GB를 초과하는 인스턴스는 일시정지할 수 없습니다.
  • 선점형 인스턴스를 일시정지할 수 있지만 인스턴스가 일시정지되기 전에 선점형 인스턴스가 종료될 수 있습니다.
  • 컨피덴셜 VM은 일시정지할 수 없습니다.
  • CSEK 보호 디스크가 연결된 VM은 정지할 수 없습니다.

로컬 SSD

일반적으로 로컬 SSD를 사용하는 VM 인스턴스를 전송하면 로컬 SSD 드라이브에 있는 모든 데이터가 삭제되며, 이것은 인스턴스를 중지할 때와 동일한 동작입니다.

자세한 내용은 로컬 SSD 문서를 참조하세요.

선점형 VM

선점형 VM을 정지할 수 있지만 정지 작업이 완료되기 전에 선점(선점 앞에 나오는 사전 경고 아님)이 발생하면 정지가 종료되고 인스턴스가 선점됩니다.

OS 호환성

Compute Engine에서 제공하는 대부분의 운영체제는 일시정지 및 재개 기능을 지원하지만 일부 OS에서는 지원하지 않습니다. 전체 목록은 OS 세부정보 페이지를 참조하세요.

가격 책정

인스턴스를 일시정지하면 다음 항목에 대한 요금이 청구됩니다.

  • 인스턴스 메모리(일시정지된 VM 인스턴스의 가격 책정 참조)
  • 부팅 디스크 및 인스턴스에 연결된 추가 디스크의 영구 디스크 사용량(영구 디스크 가격 책정 참조)
  • 인스턴스에 연결된 모든 고정 IP
  • VM을 일시정지하면 소프트웨어 라이선스 요금을 절약할 수 있습니다. 예를 들어 Windows VM을 일시정지해도 Windows 라이선스 요금이 발생하지 않습니다. 다른 이미지의 라이선스 요금은 이용약관이 다를 수 있으며 일시정지 시 요금이 부과될 수 있습니다.

인스턴스 일시정지

인스턴스를 일시정지하려면 Google Cloud Console, gcloud CLI, API 또는 Cloud 클라이언트 라이브러리를 사용합니다.

게스트 환경에 내장된 표준 프로세스를 사용하여 인스턴스를 정지할 수 없습니다. Google Cloud Console, Google Cloud CLI 또는 API를 사용하여 인스턴스를 정지할 수 있습니다.

인스턴스가 시작된 후 너무 빨리 트리거되면 정지 작업이 실패할 수 있습니다. 정지 작업이 성공하려면 인스턴스가 완전히 시작되어야 합니다(게스트 에이전트와 같은 프로세스 포함).

Console

  1. Google Cloud 콘솔에서 VM 인스턴스 페이지로 이동합니다.

    VM 인스턴스 페이지로 이동

  2. 일시정지할 인스턴스를 하나 이상 선택합니다.

  3. 일시정지를 클릭합니다.

  4. 메시지가 표시된 상태에서 로컬 SSD 데이터를 삭제하려면 SSD 콘텐츠 삭제를 선택합니다. 인스턴스가 재개되면 인스턴스의 모든 로컬 SSD 데이터가 삭제됩니다.

gcloud

Google Cloud CLI에서 인스턴스를 정지하려면 다음을 실행합니다.

 gcloud compute instances suspend VM_NAME

인스턴스를 일시정지하도록 요청한 후 Compute Engine에서 인스턴스에 필요한 모든 데이터를 보존하는 데는 약간의 시간이 걸릴 수 있습니다. 이 시간 동안 계속 실행되는 인스턴스에는 여전히 요금이 청구됩니다.

일시정지된 인스턴스는 SUSPENDED 상태로 표시됩니다. describe 요청을 하여 인스턴스의 상태를 확인합니다.

gcloud compute instances describe VM_NAME

로컬 SSD 데이터가 있는 인스턴스를 중지하려면 --discard-local-ssd 플래그를 제공해야 합니다.

gcloud compute instances suspend VM_NAME --discard-local-ssd

--discard-local-ssd 또는 --discard-local-ssd=True를 사용하면 로컬 SSD의 콘텐츠가 삭제됩니다. Compute Engine --discard-local-ssd=False는 현재 공개 미리보기 상태입니다. 이 플래그를 사용하면 중지 기간 동안 최대 16개까지 로컬 SSD 디스크의 콘텐츠가 저장됩니다. 자세한 내용은 로컬 SSD 문서를 참조하세요.

Go

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
)

// 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
}

자바


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

API에서 instances.suspend 메서드를 사용하여 요청합니다.

https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/suspend

다음을 바꿉니다.

  • PROJECT_ID: 프로젝트 ID입니다.
  • ZONE: VM의 영역입니다.
  • VM_NAME: 일시정지하려는 인스턴스입니다.

인스턴스를 일시정지하도록 요청한 후 Compute Engine에서 인스턴스에 필요한 모든 데이터를 보존하는 데는 약간의 시간이 걸릴 수 있습니다. 이 시간 동안 계속 실행되는 인스턴스에는 요금이 청구됩니다.

Compute Engine에서 SUSPENDED 상태로 일시정지된 인스턴스를 표시합니다. GET 요청을 하여 인스턴스의 상태를 확인합니다.

GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME

인스턴스의 상태는 상태 필드에 표시됩니다. 예를 들면 다음과 같습니다.

...
"zone": "https://content.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a",
"status": "SUSPENDED",
"name": "example-vm",
...

{maximum_local_ssd_disks_for_suspend}개 이상로컬 SSD 디스크가 있는 인스턴스를 중지하려면 discardLocalSsd 쿼리 매개변수를 제공하여 로컬 SSD 데이터를 삭제해야 합니다.

https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/suspend?discardLocalSsd=true

일시정지된 인스턴스 재개

VM이 있는 영역에 충분한 용량이 있는 경우에만 인스턴스를 재개할 수 있습니다. 대부분의 경우에는 문제가 되지 않지만 용량 문제가 발생하면 나중에 재개 요청을 다시 시도하세요.

일시정지된 인스턴스를 재개하려면 Google Cloud Console, gcloud CLI, API 또는 Cloud 클라이언트 라이브러리를 사용합니다.

Console

  1. Google Cloud 콘솔에서 VM 인스턴스 페이지로 이동합니다.

    VM 인스턴스 페이지로 이동

  2. 재개할 인스턴스를 하나 이상 선택합니다.

  3. 시작/재개를 클릭합니다.

gcloud

Google Cloud CLI에서 인스턴스를 다시 시작하려면 다음을 실행합니다.

 gcloud compute instances resume VM_NAME

인스턴스를 재개하도록 요청한 후 Compute Engine에서 인스턴스에 필요한 모든 데이터를 복원하는 데 약간의 시간이 걸릴 수 있습니다. 이 시간 동안 재개되는 인스턴스에는 여전히 요금이 청구됩니다.

인스턴스가 RUNNING으로 표시되면 인스턴스가 재개된 것입니다. describe 요청을 하여 인스턴스의 상태를 확인합니다.

gcloud compute instances describe VM_NAME

Go

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
)

// 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
}

자바


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 메서드에 대해 요청을 실행합니다.

https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/resume

다음을 바꿉니다.

  • PROJECT_ID: 이 요청의 프로젝트 ID입니다.
  • ZONE: VM의 영역입니다.
  • VM_NAME: 재개할 인스턴스입니다.

인스턴스를 재개하도록 요청한 후 Compute Engine에서 인스턴스에 필요한 모든 데이터를 복원하는 데 약간의 시간이 걸릴 수 있습니다. 이 시간 동안 재개되는 인스턴스에는 여전히 요금이 청구됩니다.

재개가 완료되면 Compute Engine에서 인스턴스를 RUNNING 상태로 표시합니다. GET 요청을 하여 인스턴스의 상태를 확인합니다.

GET https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/instances/example-instance

인스턴스의 상태는 상태 필드에 표시됩니다. 예를 들면 다음과 같습니다.

...
"zone": "https://content.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a",
"status": "RUNNING",
"name": "example-instance",
...

일시정지 절차

일시정지를 요청하면 VM 인스턴스에 ACPI 일시정지 신호를 보냅니다. VM이 몇 분 내에 ACPI S3 일시정지 신호에 응답하지 않으면 Compute Engine은 일시정지 시도를 취소하고 VM을 RUNNING 상태로 반환합니다.

다음 표에서는 VM 인스턴스를 일시정지할 때 관련 리소스에 미치는 영향을 설명합니다.

리소스 지원
메모리 메모리가 208GB 이하인 VM만 일시정지할 수 있습니다.
로컬 SSD 로컬 SSD 데이터가 삭제됩니다.
영구 디스크 영구 HDD 및 SSD 디스크가 보관됩니다.
IP 주소 임시 IP는 일시정지 중에 해제되지만 고정 IP는 VM 인스턴스에 연결된 상태로 유지됩니다. 임시 IP를 유지하려면 이를 승격합니다.
VM 구성(예: 머신 유형, 메타데이터, 라벨 등) 인스턴스가 재개되면 임시 IP 주소를 제외한 모든 VM 구성이 보존 및 복원됩니다.

일시정지 및 재개를 지원하도록 Debian VM 구성

Debian 8 및 9를 실행하는 VM은 일시정지 및 재개할 수 있지만 사전에 구성해야 합니다. Debian 인스턴스를 구성하려면 다음 옵션 A 또는 옵션 B를 완료합니다. 가능한 경우 ACPID를 구성하는 것이 좋습니다(옵션 A).

옵션 A

이 옵션은 절전 모드 버튼 이벤트를 처리하도록 ACPID를 구성하고 절전 모드 이벤트를 처리하기 위한 셸 스크립트를 추가합니다.

  1. ssh를 사용하여 VM 인스턴스에 연결합니다.

    gcloud compute ssh VM_NAME
    
  2. VM 인스턴스에서 acpi 폴더 아래에 디렉터리를 만듭니다.

    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
    

옵션 B

  1. ssh를 사용하여 VM 인스턴스에 연결합니다.

    gcloud compute ssh VM_NAME
    
  2. VM 인스턴스에 dbus를 설치합니다.

    sudo apt-get install dbus
    
  3. logind를 다시 시작합니다.

    sudo systemctl restart systemd-logind.service
    

다음 단계