Sospendi o ripristina un'istanza Compute Engine

Questo documento spiega come sospendere o ripristinare le istanze Compute Engine. Per scoprire di più sulla sospensione, l'arresto o la reimpostazione delle istanze, consulta Sospendi, arresta o reimposta le istanze Compute Engine.

Se vuoi mantenere la tua istanza Compute Engine, ma non vuoi sostenere addebiti quando non è in uso, puoi sospenderla. La sospensione di un'istanza la conserva e ne esegue la migrazione dei contenuti della memoria allo spazio di archiviazione. Dopo aver ripristinato l'istanza, Compute Engine esegue la migrazione della memoria dell'istanza dallo spazio di archiviazione all'istanza e l'istanza riprende a essere eseguita.

La sospensione di un'istanza Compute Engine è utile per:

  • Ambienti di sviluppo e test che non vengono utilizzati completamente durante i periodi non di punta, ad esempio la sera o nei fine settimana, e che vuoi mantenere per risparmiare sui costi o per un'inizializzazione più rapida rispetto alla creazione di nuove istanze.

  • Applicazioni che richiedono un lungo periodo di inizializzazione dopo l'avvio dell'istanza, ma prima che l'applicazione sia pronta a gestire la prima richiesta, ad esempio workstation di sviluppo virtuali o applicazioni Java complesse.

Prima di iniziare

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per sospendere o riattivare un'istanza di computing, chiedi all'amministratore di concederti il ruolo IAM Compute Instance Admin (v1) (roles/compute.instanceAdmin.v1) sull'istanza. Per saperne di più sulla concessione dei ruoli, consulta Gestisci l'accesso a progetti, cartelle e organizzazioni.

Questo ruolo predefinito contiene le autorizzazioni necessarie per sospendere o riattivare un'istanza di computing. Per vedere quali sono esattamente le autorizzazioni richieste, espandi la sezione Autorizzazioni obbligatorie:

Autorizzazioni obbligatorie

Per sospendere o ripristinare un'istanza di computing sono necessarie le seguenti autorizzazioni:

  • Per sospendere un'istanza: compute.instances.suspend
  • Per ripristinare un'istanza: compute.instances.resume

Potresti anche ottenere queste autorizzazioni con ruoli personalizzati o altri ruoli predefiniti.

Limitazioni

Quando sospendi un'istanza di computing, si applicano le seguenti limitazioni:

  • Puoi sospendere un'istanza solo se il sistema operativo guest lo supporta. Per ulteriori informazioni, vedi Dettagli del sistema operativo.

  • Puoi sospendere un'istanza che utilizza Debian 8 o 9 come sistema operativo guest solo se configuri il sistema operativo prima di sospendere l'istanza.

  • Puoi sospendere un'istanza solo per un massimo di 60 giorni prima che Compute Engine ne modifichi automaticamente lo stato in TERMINATED.

  • Puoi sospendere le VM spot o le istanze preemptible. Tuttavia, se Compute Engine prerilascia l'istanza prima del completamento dell'operazione di sospensione, la termina e prerilascia le istanze.

  • Non puoi sospendere le istanze con GPU collegate.

  • Non puoi sospendere le istanze Bare Metal.

  • Non puoi sospendere le Confidential VM.

  • Non puoi sospendere le istanze utilizzando le procedure standard integrate nel loro ambiente ospite. I comandi come systemctl suspend in Ubuntu 16.04 o versioni successive non sono supportati. Se viene chiamato, Compute Engine ignora l'indicatore in-guest.

  • Non puoi sospendere istanze con più di 208 GB di memoria.

  • Non puoi sospendere le istanze a cui sono collegati dischi protetti da CSEK.

Attivare le operazioni di sospensione in Debian 8 o 9

Se un'istanza di computing esegue Debian 8 e 9 come sistema operativo guest, prima di sospendere l'istanza, devi abilitare le operazioni di sospensione e ripristino eseguendo una delle seguenti operazioni:

Configura ACPID

Per attivare l'operazione di sospensione e ripresa in Debian 8 o 9, puoi configurare il daemon ACPID (Advanced Configuration and Power Interface events Daemon) per gestire l'evento del pulsante di sospensione. Dopo aver attivato l'evento del pulsante di sospensione profonda, puoi aggiungere uno script shell per la gestione dell'evento di sospensione come descritto in questa sezione.

Per configurare ACPID in modo che supporti le operazioni di sospensione e ripresa, procedi nel seguente modo:

  1. Se non l'hai ancora fatto, connettiti all'istanza Linux.

  2. Crea la cartella events nella cartella acpi:

    sudo mkdir -p /etc/acpi/events/
    
  3. Configura ACPID per gestire l'evento del pulsante di sospensione:

    cat <<EOF | sudo tee /etc/acpi/events/sleepbtn-acpi-support
    event=button[ /]sleep
    action=/etc/acpi/sleepbtn-acpi-support.sh
    EOF
    
  4. Crea lo script di gestione dell'evento di sospensione:

    cat <<EOF | sudo tee /etc/acpi/sleepbtn-acpi-support.sh
    #!/bin/sh
    echo mem > /sys/power/state
    EOF
    
  5. Configura le autorizzazioni per lo script:

    sudo chmod 755 /etc/acpi/sleepbtn-acpi-support.sh
    
  6. Per applicare le modifiche, riavvia ACPID:

    sudo systemctl restart acpid.service
    

Installare D-Bus

Per attivare l'operazione di sospensione e ripristino in Debian 8 o 9, puoi installare D-Bus.

Per installare D-Bus nel sistema operativo guest dell'istanza di calcolo quando il sistema operativo utilizza Debian 8 o 9, procedi nel seguente modo:

  1. Se non l'hai ancora fatto, connettiti all'istanza Linux.

  2. Installa D-Bus:

    sudo apt-get install dbus
    
  3. Per applicare le modifiche, riavvia logind:

    sudo systemctl restart systemd-logind.service
    

Sospendi un'istanza

Se il sistema operativo guest della tua istanza di calcolo utilizza Debian 8 o 9, prima di sospendere l'istanza devi configurare il sistema operativo guest per supportare le operazioni di sospensione e ripristino come descritto in questo documento.

Per sospendere un'istanza, utilizza uno dei seguenti metodi a seconda che all'istanza siano collegati dischi SSD locali:

Sospendi un'istanza senza dischi SSD locali

Puoi sospendere più istanze di computing contemporaneamente o istanze singole. Per più istanze, utilizza la console Trusted Cloud o, per le istanze situate nella stessa zona, Google Cloud CLI. Per le istanze singole, seleziona una delle seguenti opzioni:

Console

  1. Nella console Trusted Cloud , vai alla pagina Istanze VM.

    Vai a Istanze VM

  2. Seleziona una o più istanze da sospendere.

  3. Fai clic su Sospendi, quindi su Sospendi per confermare.

gcloud

Per sospendere una o più istanze in una singola zona, utilizza il comando gcloud compute instances suspend:

gcloud compute instances suspend INSTANCE_NAMES \
    --zone=ZONE

Sostituisci quanto segue:

  • INSTANCE_NAMES: un elenco separato da spazi dei nomi delle istanze, ad esempio instance-01 instance-02 instance-03.

  • ZONE: la zona in cui si trovano le istanze.

Vai

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

Per sospendere un'istanza, effettua una richiesta POST al metodo instances.suspend:

POST https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend

Sostituisci quanto segue:

  • PROJECT_ID: l'ID del progetto in cui si trova l'istanza

  • ZONE: la zona in cui si trova l'istanza

  • INSTANCE_NAME: il nome dell'istanza

Sospendi un'istanza con dischi SSD locali

In base al numero di istanze di calcolo che vuoi sospendere contemporaneamente e se devi conservare i dati dei dischi SSD locali collegati, procedi nel seguente modo:

  • Per conservare i dati dei dischi SSD locali collegati a un'istanza (escluse le istanze Z3), sospendi l'istanza utilizzando gcloud CLI o l'API REST.

  • Per sospendere più istanze contemporaneamente, utilizza la console Trusted Cloud o, per le istanze situate nella stessa zona, gcloud CLI.

Per sospendere una o più istanze con dischi SSD locali collegati, seleziona una delle seguenti opzioni:

Console

  1. Nella console Trusted Cloud , vai alla pagina Istanze VM.

    Vai a Istanze VM

  2. Seleziona una o più istanze da sospendere.

  3. Fai clic su Sospendi, quindi su Sospendi per confermare.

gcloud

Quando sospendi una o più istanze in una singola zona con dischi SSD locali collegati, specifica se desideri eliminare o conservare i dati dell'SSD locale come segue:

  • Per eliminare i dati dell'SSD locale, utilizza il comando gcloud compute instances suspend con il flag --discard-local-ssd=true:

    gcloud compute instances suspend INSTANCE_NAMES \
        --discard-local-ssd=true \
        --zone=ZONE
    
  • Per conservare i dati dell'SSD locale, utilizza il comando gcloud beta compute instances suspend con il flag --discard-local-ssd=false:

    gcloud beta compute instances suspend INSTANCE_NAMES \
        --discard-local-ssd=false \
        --zone=ZONE
    

Sostituisci quanto segue:

  • INSTANCE_NAMES: un elenco separato da spazi dei nomi delle istanze, ad esempio instance-01 instance-02 instance-03.

  • ZONE: la zona in cui si trovano le istanze.

REST

Quando sospendi un'istanza a cui sono collegati dischi SSD locali, specifica se desideri eliminare o conservare i dati dell'SSD locale come segue:

  • Per eliminare i dati dell'SSD locale, effettua una richiesta POST al metodo instances.suspend. Nell'URL della richiesta, includi il parametro di query discardLocalSsd impostato su true:

    POST https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend?discardLocalSsd=true
    
  • Per conservare i dati dell'SSD locale, invia una richiesta POST al metodo beta.instances.suspend. Nell'URL della richiesta, includi il parametro di query discardLocalSsd impostato su false:

    POST https://compute.s3nsapis.fr/compute/beta/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend?discardLocalSsd=false
    

Sostituisci quanto segue:

  • PROJECT_ID: l'ID del progetto in cui si trova l'istanza

  • ZONE: la zona in cui si trova l'istanza

  • INSTANCE_NAME: il nome dell'istanza

Ripristinare un'istanza sospesa

Prima di riprendere un'istanza di calcolo sospesa, tieni presente quanto segue:

  • Puoi riprendere un'istanza solo se c'è capacità sufficiente nella zona in cui si trova l'istanza. In genere non è un problema. Se hai difficoltà a riprendere un'istanza, riprova più tardi.

  • Se hai collegato dischi SSD locali all'istanza e hai scelto di conservare i dati dell'SSD locale quando l'hai sospesa, potresti dover rimontare i dischi SSD locali dopo averla riattivata. Per saperne di più, scopri come rimontare i dischi non di avvio nelle istanze Linux o nelle istanze Windows.

Puoi ripristinare più istanze contemporaneamente o istanze singole. Per più istanze, utilizza la console Trusted Cloud o, per istanze situate nella stessa zona, gcloud CLI. Per le istanze singole seleziona una delle seguenti opzioni:

Console

  1. Nella console Trusted Cloud , vai alla pagina Istanze VM.

    Vai a Istanze VM

  2. Seleziona una o più istanze sospese da ripristinare.

  3. Fai clic su Avvia / Riprendi, quindi su Avvia.

gcloud

Per ripristinare una o più istanze sospese in una singola zona, utilizza il comando gcloud compute instances resume:

gcloud compute instances resume INSTANCE_NAMES \
    --zone=ZONE

Sostituisci quanto segue:

  • INSTANCE_NAMES: un elenco separato da spazi dei nomi delle istanze, ad esempio instance-01 instance-02 instance-03.

  • ZONE: la zona in cui si trovano le istanze sospese.

Vai

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

Per riattivare un'istanza sospesa, invia una richiesta POST al metodo instances.resume:

POST https://compute.s3nsapis.fr/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/resume

Sostituisci quanto segue:

  • INSTANCE_NAME: il nome dell'istanza sospesa da riattivare.

  • PROJECT_ID: l'ID del progetto in cui si trova l'istanza sospesa.

  • ZONE: la zona in cui si trova l'istanza sospesa.

Passaggi successivi