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 인스턴스 관리자(v1)(roles/compute.instanceAdmin.v1) IAM 역할을 부여해 달라고 요청하세요. 역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

이 사전 정의된 역할에는 컴퓨팅 인스턴스를 일시중지 또는 재개하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 펼치세요.

필수 권한

컴퓨팅 인스턴스를 일시중지하거나 재개하려면 다음 권한이 필요합니다.

  • 인스턴스 일시중지: compute.instances.suspend
  • 인스턴스 재개: compute.instances.resume

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

제한사항

컴퓨팅 인스턴스를 일시중지할 때는 다음과 같은 제한사항이 적용됩니다.

  • 게스트 OS에서 지원되는 경우에만 인스턴스를 일시중지할 수 있습니다. 자세한 내용은 운영체제 세부정보를 참조하세요.

  • 인스턴스를 일시중지하기 전에 OS를 구성한 경우 Debian 8 또는 9를 게스트 OS로 사용하는 인스턴스만 일시중지할 수 있습니다.

  • Compute Engine이 상태를 TERMINATED로 자동으로 전환하기 전 최대 60일까지만 인스턴스를 일시중지할 수 있습니다.

  • 스팟 VM 또는 선점형 인스턴스를 일시중지할 수 있지만 일시중지 작업이 완료되기 전에 Compute Engine이 인스턴스를 선점할 경우에는 Compute Engine이 일시중지 작업을 끝내고 인스턴스를 선점합니다.

  • GPU가 연결된 인스턴스는 일시중지할 수 없습니다.

  • 베어메탈 인스턴스는 일시중지할 수 없습니다.

  • 컨피덴셜 VM은 일시중지할 수 없습니다.

  • 게스트 환경에 빌드된 표준 프로세스를 사용해서는 인스턴스를 일시중지할 수 없습니다. Ubuntu 16.04 이상에서 systemctl suspend와 같은 명령어는 지원되지 않습니다. 호출하면 Compute Engine이 게스트 내 속성을 무시합니다.

  • 메모리가 208GB를 초과하는 인스턴스는 일시중지할 수 없습니다.

  • CSEK 보호 디스크가 연결된 인스턴스는 일시중지할 수 없습니다.

Debian 8 또는 9에서 일시중지 작업 사용 설정

컴퓨팅 인스턴스에서 Debian 8 및 9가 게스트 OS로 사용되는 경우 인스턴스를 일시중지하기 전에 다음 중 하나를 수행하여 일시중지 및 재개 작업을 사용 설정해야 합니다.

ACPID 구성

Debian 8 또는 9에서 일시중지 및 재개 작업을 사용 설정하려면 절전 모드 버튼 이벤트를 처리하도록 고급 구성 및 전원 인터페이스 이벤트 데몬(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. 일시중지할 인스턴스를 하나 이상 선택합니다.

  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

인스턴스를 일시중지하려면 POST 요청을 instances.suspend 메서드에 보냅니다.

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

다음을 바꿉니다.

  • PROJECT_ID: 인스턴스가 위치한 프로젝트의 ID입니다.

  • ZONE: 인스턴스가 있는 영역입니다.

  • INSTANCE_NAME: 인스턴스 이름입니다.

로컬 SSD 디스크가 있는 인스턴스 일시중지

동시에 일시중지하려는 컴퓨팅 인스턴스 수 및 연결된 로컬 SSD 디스크의 데이터를 보존해야 하는지 여부에 따라 다음을 수행합니다.

  • 인스턴스에 연결된 로컬 SSD 디스크의 데이터를 보존하려면(Z3 인스턴스 제외) gcloud CLI 또는 REST API를 사용하여 인스턴스를 일시중지합니다.

  • 여러 인스턴스를 동시에 일시중지하려면 Google Cloud 콘솔을 사용하고, 동일 영역에 있는 인스턴스의 경우에는 gcloud CLI를 사용합니다.

로컬 SSD 디스크가 연결된 하나 이상의 인스턴스를 일시중지하려면 다음 옵션 중 하나를 선택합니다.

콘솔

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

    VM 인스턴스로 이동

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

  3. 일시중지를 클릭한 후 일시중지를 클릭하여 확인합니다.

gcloud

로컬 SSD 디스크가 연결된 단일 영역에서 하나 이상의 인스턴스를 일시중지할 때는 다음과 같이 로컬 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 데이터를 삭제하려면 POST 요청을 instances.suspend 메서드에 보냅니다. 요청 URL에 true로 설정된 discardLocalSsd 쿼리 파라미터를 포함합니다.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend?discardLocalSsd=true
    
  • 로컬 SSD 데이터를 보존하려면 POST 요청을 beta.instances.suspend 메서드에 보냅니다. 요청 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. 재개하려는 일시중지된 인스턴스를 하나 이상 선택합니다.

  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

일시중지된 인스턴스를 재개하려면 POST 요청을 instances.resume 메서드에 보냅니다.

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

다음을 바꿉니다.

  • INSTANCE_NAME: 재개할 일시중지된 인스턴스의 이름입니다.

  • PROJECT_ID: 일시중지된 인스턴스가 있는 프로젝트의 ID입니다.

  • ZONE: 일시중지된 인스턴스가 있는 영역입니다.

다음 단계