VM beenden und neu starten


In diesem Dokument wird erläutert, wie Sie eine VM-Instanz manuell beenden und neu starten sowie eine VM zurücksetzen oder neu starten.

  • Beenden Sie eine VM, wenn Sie sie nicht mehr verwenden oder eines oder mehrere ihrer Attribute ändern möchten. Wenn Sie beispielsweise die VM umbenennen, den Maschinentyp ändern, angehängte Laufwerke hinzufügen oder entfernen oder die Mindest-CPU-Plattform ändern möchten. Nachdem Sie die VM beendet haben, starten Sie sie neu, um die Arbeitslast fortzusetzen, oder löschen Sie die VM, wenn Sie sie nicht mehr benötigen.

  • Setzen Sie eine VM zurück, wenn beispielsweise die VM nicht mehr reagiert oder das Gastbetriebssystem (OS) abgestürzt ist. Nachdem Sie die VM zurückgesetzt haben, können Sie Ihre Arbeitslast fortsetzen.

  • Starten Sie eine VM innerhalb des Gastbetriebssystems neu, wenn Sie beispielsweise den Arbeitsspeicher der VM löschen und in ihrem ursprünglichen Bootstatus neu initialisieren möchten. Nach dem Neustart einer VM aus ihrem Gastbetriebssystem können Sie die Arbeitslast fortsetzen.

Hinweise

  • Richten Sie die Authentifizierung ein, falls Sie dies noch nicht getan haben. Bei der Authentifizierung wird Ihre Identität für den Zugriff auf Google Cloud-Dienste und APIs überprüft. Zur Ausführung von Code oder Beispielen aus einer lokalen Entwicklungsumgebung können Sie sich wie folgt bei Compute Engine authentifizieren.

    Wählen Sie den Tab für die Verwendung der Beispiele auf dieser Seite aus:

    Console

    Wenn Sie über die Google Cloud Console auf Google Cloud-Dienste und -APIs zugreifen, müssen Sie die Authentifizierung nicht einrichten.

    gcloud

    1. Installieren Sie die Google Cloud CLI und initialisieren Sie sie mit folgendem Befehl:

      gcloud init
    2. Legen Sie eine Standardregion und -zone fest.

    Einfach loslegen (Go)

    Wenn Sie die Go-Beispiele auf dieser Seite aus einer lokalen Entwicklungsumgebung heraus verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

    1. Installieren Sie die Google Cloud CLI.
    2. Führen Sie folgenden Befehl aus, um die gcloud CLI zu initialisieren:

      gcloud init
    3. Erstellen Sie lokale Anmeldedaten zur Authentifizierung für Ihr Google-Konto:

      gcloud auth application-default login

    Weitere Informationen: Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    Java

    Wenn Sie die Java-Beispiele auf dieser Seite aus einer lokalen Entwicklungsumgebung heraus verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

    1. Installieren Sie die Google Cloud CLI.
    2. Führen Sie folgenden Befehl aus, um die gcloud CLI zu initialisieren:

      gcloud init
    3. Erstellen Sie lokale Anmeldedaten zur Authentifizierung für Ihr Google-Konto:

      gcloud auth application-default login

    Weitere Informationen: Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    Node.js

    Wenn Sie die Node.js-Beispiele auf dieser Seite aus einer lokalen Entwicklungsumgebung heraus verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

    1. Installieren Sie die Google Cloud CLI.
    2. Führen Sie folgenden Befehl aus, um die gcloud CLI zu initialisieren:

      gcloud init
    3. Erstellen Sie lokale Anmeldedaten zur Authentifizierung für Ihr Google-Konto:

      gcloud auth application-default login

    Weitere Informationen: Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    PHP

    Wenn Sie die PHP-Beispiele auf dieser Seite aus einer lokalen Entwicklungsumgebung heraus verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

    1. Installieren Sie die Google Cloud CLI.
    2. Führen Sie folgenden Befehl aus, um die gcloud CLI zu initialisieren:

      gcloud init
    3. Erstellen Sie lokale Anmeldedaten zur Authentifizierung für Ihr Google-Konto:

      gcloud auth application-default login

    Weitere Informationen: Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    Python

    Wenn Sie die Python-Beispiele auf dieser Seite aus einer lokalen Entwicklungsumgebung heraus verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

    1. Installieren Sie die Google Cloud CLI.
    2. Führen Sie folgenden Befehl aus, um die gcloud CLI zu initialisieren:

      gcloud init
    3. Erstellen Sie lokale Anmeldedaten zur Authentifizierung für Ihr Google-Konto:

      gcloud auth application-default login

    Weitere Informationen: Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    REST

    Verwenden Sie die von der gcloud CLI bereitgestellten Anmeldedaten, um die REST API-Beispiele auf dieser Seite in einer lokalen Entwicklungsumgebung zu verwenden.

      Installieren Sie die Google Cloud CLI und initialisieren Sie sie mit folgendem Befehl:

      gcloud init

Erforderliche Rollen

Bitten Sie Ihren Administrator, Ihnen die IAM-Rolle Compute-Instanzadministrator (Version 1) (roles/compute.instanceAdmin.v1) für das Projekt zu gewähren, um die Berechtigungen zu erhalten, die Sie zum Beenden und zum Neustarten einer VM benötigen. Weitere Informationen zum Zuweisen von Rollen finden Sie unter Zugriff verwalten.

Diese vordefinierte Rolle enthält die Berechtigungen, die zum Beenden und Neustarten einer VM erforderlich sind. Erweitern Sie den Abschnitt Erforderliche Berechtigungen, um die erforderlichen Berechtigungen anzuzeigen:

Erforderliche Berechtigungen

Die folgenden Berechtigungen sind erforderlich, um eine VM zu beenden und neu zu starten:

  • So beenden Sie eine VM: compute.instances.stop auf der VM
  • So beenden Sie eine VM innerhalb des Gastbetriebssystems: compute.instances.setMetadata auf der VM, wenn öffentliche SSH-Schlüssel auf Instanzebene verwendet werden.
  • So starten Sie eine VM neu: compute.instances.start auf der VM
  • So starten Sie eine VM neu, die Verschlüsselungsschlüssel verwendet: compute.instances.startWithEncryptionKey auf der VM
  • So setzen Sie eine VM zurück: compute.instances.reset auf der VM
  • So starten Sie eine VM innerhalb des Gastbetriebssystems neu: compute.instances.setMetadata auf der VM

Sie können diese Berechtigungen auch mit benutzerdefinierten Rollen oder anderen vordefinierten Rollen erhalten.

VM beenden

Wenn Sie eine laufende VM beenden, geschieht Folgendes:

  1. Compute Engine sendet das Signal ACPI Shutdown an die VM und wartet eine kurze Zeit, bis das Gastbetriebssystem ordnungsgemäß heruntergefahren wurde. Dann setzt Compute Engine den Status der VM zuerst auf STOPPING und wechselt dann innerhalb einer Minute auf TERMINATED.

  2. Die VM wird in den Power-on-Zustand zurückgesetzt und behält ihre internen IP-Adressen, MAC-Adressen, Konfigurationseinstellungen und Metadaten bei. Die VM verliert jedoch ihre In-Memory-Daten und den VM-Status. Wenn Sie die In-Memory-Daten und den VM-Status beibehalten möchten, halten Sie stattdessen die VM an.

Wenn Sie der VM Ressourcen zugeordnet haben, bleiben diese Ressourcen so lange angehängt, bis Sie sie manuell trennen oder die VM löschen. Wenn an die VM lokale SSD-Laufwerke angehängt sind, werden durch das Beenden der VM standardmäßig alle Daten auf den lokalen SSD-Laufwerken verworfen. Wenn Sie die Daten auf den lokalen SSD-Laufwerken beibehalten möchten, müssen Sie die VM mithilfe der gcloud CLI mit dem Flag --discard-local-ssd=false beenden. Weitere Informationen finden Sie unter VM mit lokaler SSD beenden.

Wählen Sie eine der in diesem Dokument beschriebenen Methoden aus, um eine VM zu beenden:

Nachdem Sie eine VM beendet haben, können Sie sie entweder neu starten oder löschen. Wenn Sie die VM nicht neu starten möchten, sollten Sie sie löschen.

VM über Google Cloud beenden

Wenn Sie mehrere VMs gleichzeitig beenden möchten, verwenden Sie die Google Cloud Console.

Console

So beenden Sie eine oder mehrere VMs:

  1. Rufen Sie in der Google Cloud Console die Seite VM-Instanzen auf.

    Zur Seite „VM-Instanzen“

  2. Wählen Sie die VMs aus, die beendet werden sollen.

  3. Klicken Sie auf Beenden und dann zur Bestätigung auf Beenden.

gcloud

Zum Beenden einer VM verwenden Sie den Befehl gcloud compute instances stop.

gcloud compute instances stop VM_NAME \
    --project=PROJECT_ID \
    --zone=ZONE

Ersetzen Sie Folgendes:

  • VM_NAME: der Name der VM.

  • PROJECT_ID: die Projekt-ID des Projekts, in dem sich die VM befindet.

  • ZONE ist die Zone, in der sich die VM befindet.

Wenn Sie ein lokales SSD-Laufwerk an die VM angehängt haben und die lokalen SSD-Daten nach dem Beenden der VM beibehalten möchten, verwenden Sie den Befehl gcloud beta compute instances stop mit dem Flag --discard-local-ssd=false.

gcloud beta compute instances stop VM_NAME \
    --discard-local-ssd=false \
    --project=PROJECT_ID \
    --zone=ZONE

Einfach loslegen (Go)

import (
	"context"
	"fmt"
	"io"

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

// stopInstance stops a started Google Compute Engine instance
func stopInstance(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.StopInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
	}

	op, err := instancesClient.Stop(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to stop 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 stopped\n")

	return nil
}

Java


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.StopInstanceRequest;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class StopInstance {

  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 stop.
     */
    String project = "your-project-id";
    String zone = "zone-name";
    String instanceName = "instance-name";

    stopInstance(project, zone, instanceName);
  }

  // Stops a started Google Compute Engine instance.
  public static void stopInstance(String project, String zone, String instanceName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    /* Initialize client that will be used to send requests. This client only needs to be created
       once, and can be reused for multiple requests. After completing all of your requests, call
       the `instancesClient.close()` method on the client to safely
       clean up any remaining background resources. */
    try (InstancesClient instancesClient = InstancesClient.create()) {

      StopInstanceRequest stopInstanceRequest = StopInstanceRequest.newBuilder()
          .setProject(project)
          .setZone(zone)
          .setInstance(instanceName)
          .build();

      OperationFuture<Operation, Operation> operation = instancesClient.stopAsync(
          stopInstanceRequest);
      Operation response = operation.get(3, TimeUnit.MINUTES);

      if (response.getStatus() == Status.DONE) {
        System.out.println("Instance stopped successfully ! ");
      }
    }
  }
}

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');

async function stopInstance() {
  const instancesClient = new compute.InstancesClient();

  const [response] = await instancesClient.stop({
    project: projectId,
    zone,
    instance: instanceName,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

  // Wait for the operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log('Instance stopped.');
}

stopInstance();

PHP

use Google\Cloud\Compute\V1\Client\InstancesClient;
use Google\Cloud\Compute\V1\StopInstanceRequest;

/**
 * Stops 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 stop.
  *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 * @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
 */
function stop_instance(
    string $projectId,
    string $zone,
    string $instanceName
) {
    // Stop the Compute Engine instance using InstancesClient.
    $instancesClient = new InstancesClient();
    $request = (new StopInstanceRequest())
        ->setInstance($instanceName)
        ->setProject($projectId)
        ->setZone($zone);
    $operation = $instancesClient->stop($request);

    // Wait for the operation to complete.
    $operation->pollUntilComplete();
    if ($operation->operationSucceeded()) {
        printf('Instance %s stopped successfully' . PHP_EOL, $instanceName);
    } else {
        $error = $operation->getError();
        printf('Failed to stop 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 stop_instance(project_id: str, zone: str, instance_name: str) -> None:
    """
    Stops 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 your want to stop.
    """
    instance_client = compute_v1.InstancesClient()

    operation = instance_client.stop(
        project=project_id, zone=zone, instance=instance_name
    )
    wait_for_extended_operation(operation, "instance stopping")

REST

Senden Sie zum Beenden einer VM eine POST-Anfrage an die Methode instances.stop.

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

Ersetzen Sie Folgendes:

  • VM_NAME: der Name der VM.

  • PROJECT_ID: die Projekt-ID des Projekts, in dem sich die VM befindet.

  • ZONE ist die Zone, in der sich die VM befindet.

VM innerhalb des Gastbetriebssystems beenden

Wählen Sie einen der folgenden Tabs aus, um eine VM innerhalb des Gastbetriebssystems zu beenden, wenn Sie mit der VM verbunden sind.

Linux

Wählen Sie eine der folgenden Methoden, um eine Linux-VM zu beenden:

  • Führen Sie für ein ordnungsgemäßes Herunterfahren den folgenden Befehl aus, damit die VM Shutdown-Skripts ausführen kann, bevor das Signal "ACPI Shutdown" an die VM gesendet wird:

    sudo shutdown -h now
    
  • Führen Sie andernfalls den folgenden Befehl aus, um das Herunterfahren zu erzwingen:

    sudo poweroff
    

Windows

Wählen Sie eine der folgenden Methoden aus, um eine Windows-VM zu beenden:

  • Führen Sie für ein ordnungsgemäßes Herunterfahren den folgenden Befehl aus, damit die VM Shutdown-Skripts ausführen kann, bevor das Signal "ACPI Shutdown" an die VM gesendet wird:

    shutdown /s
    
  • Führen Sie andernfalls den folgenden Befehl aus, um das Herunterfahren zu erzwingen:

    shutdown /f
    

VM neu starten

Sie können eine angehaltene VM nur dann neu starten, wenn sie den Status TERMINATED hat. Wählen Sie eine der folgenden in diesem Dokument beschriebenen Methoden aus, um eine VM neu zu starten:

VM ohne verschlüsselte Laufwerke neu starten

Starten Sie eine beendete VM neu, die keine verschlüsselten Laufwerke verwendet (Standard). Wenn Sie mehrere VMs gleichzeitig neu starten möchten, verwenden Sie die Google Cloud Console.

Console

So starten Sie eine oder mehrere VMs neu:

  1. Rufen Sie in der Google Cloud Console die Seite VM-Instanzen auf.

    Zur Seite „VM-Instanzen“

  2. Wählen Sie eine oder mehrere VMs aus.

  3. Klicken Sie auf Starten/Fortsetzen.

gcloud

Zum Neustarten einer VM verwenden Sie den Befehl gcloud compute instances start:

gcloud compute instances start VM_NAME \
    --project=PROJECT_ID \
    --zone=ZONE

Ersetzen Sie Folgendes:

  • VM_NAME: der Name der VM.

  • PROJECT_ID: die Projekt-ID des Projekts, in dem sich die VM befindet.

  • ZONE ist die Zone, in der sich die VM befindet.

Einfach loslegen (Go)

import (
	"context"
	"fmt"
	"io"

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

// startInstance starts a stopped Google Compute Engine instance (with unencrypted disks).
func startInstance(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.StartInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
	}

	op, err := instancesClient.Start(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to start 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 started\n")

	return nil
}

Java


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.StartInstanceRequest;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class StartInstance {

  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 start. */
    String project = "your-project-id";
    String zone = "zone-name";
    String instanceName = "instance-name";

    startInstance(project, zone, instanceName);
  }

  // Starts a stopped Google Compute Engine instance (with unencrypted disks).
  public static void startInstance(String project, String zone, String instanceName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    /* Initialize client that will be used to send requests. This client only needs to be created
       once, and can be reused for multiple requests. After completing all of your requests, call
       the `instancesClient.close()` method on the client to safely
       clean up any remaining background resources. */
    try (InstancesClient instancesClient = InstancesClient.create()) {

      // Create the request.
      StartInstanceRequest startInstanceRequest = StartInstanceRequest.newBuilder()
          .setProject(project)
          .setZone(zone)
          .setInstance(instanceName)
          .build();

      OperationFuture<Operation, Operation> operation = instancesClient.startAsync(
          startInstanceRequest);

      // Wait for the operation to complete.
      Operation response = operation.get(3, TimeUnit.MINUTES);

      if (response.getStatus() == Status.DONE) {
        System.out.println("Instance started successfully ! ");
      }
    }
  }
}

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');

async function startInstance() {
  const instancesClient = new compute.InstancesClient();

  const [response] = await instancesClient.start({
    project: projectId,
    zone,
    instance: instanceName,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

  // Wait for the operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log('Instance started.');
}

startInstance();

PHP

use Google\Cloud\Compute\V1\Client\InstancesClient;
use Google\Cloud\Compute\V1\StartInstanceRequest;

/**
 * Starts a stopped 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 stop.
  *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 * @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
 */
function start_instance(
    string $projectId,
    string $zone,
    string $instanceName
) {
    // Start the Compute Engine instance using InstancesClient.
    $instancesClient = new InstancesClient();
    $request = (new StartInstanceRequest())
        ->setInstance($instanceName)
        ->setProject($projectId)
        ->setZone($zone);
    $operation = $instancesClient->start($request);

    // Wait for the operation to complete.
    $operation->pollUntilComplete();
    if ($operation->operationSucceeded()) {
        printf('Instance %s started successfully' . PHP_EOL, $instanceName);
    } else {
        $error = $operation->getError();
        printf('Failed to start 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 start_instance(project_id: str, zone: str, instance_name: str) -> None:
    """
    Starts a stopped 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 your want to start.
    """
    instance_client = compute_v1.InstancesClient()

    operation = instance_client.start(
        project=project_id, zone=zone, instance=instance_name
    )

    wait_for_extended_operation(operation, "instance start")

REST

Senden Sie zum Neustart einer VM eine POST-Anfrage an die Methode instances.start.

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

Ersetzen Sie Folgendes:

  • VM_NAME ist der Name der neu zu startenden VM.

  • PROJECT_ID: die Projekt-ID des Projekts, in dem sich die VM befindet.

  • ZONE ist die Zone, in der sich die VM befindet.

VM mit verschlüsselten Laufwerken neu starten

Sie können eine angehaltene VM neu starten, die vom Kunden bereitgestellte Verschlüsselungsschlüssel verwendet, um die an die VM angehängten nichtflüchtigen Speicher zu verschlüsseln.

Console

So starten Sie eine VM, die verschlüsselte Laufwerke verwendet, neu:

  1. Rufen Sie in der Google Cloud Console die Seite VM-Instanzen auf.

    Zur Seite „VM-Instanzen“

  2. Wählen Sie die neu zu startende VM aus.

  3. Klicken Sie auf Starten/Fortsetzen.

  4. Geben Sie Verschlüsselungsschlüssel für alle verschlüsselten Laufwerke an, die an diese VM angehängt sind, und klicken Sie dann auf Start.

gcloud

Verwenden Sie den Befehl gcloud compute instances start mit dem Flag --csek-key-file, um eine VM neu zu starten, die verschlüsselte Laufwerke verwendet. Wenn Sie einen mit RSA verpackten Schlüssel verwenden, nutzen Sie stattdessen den Befehl gcloud beta compute instances start.

gcloud compute instances start VM_NAME \
    --csek-key-file=ENCRYPTION_KEY_FILE \
    --project=PROJECT_ID \
    --zone=ZONE

Ersetzen Sie Folgendes:

  • VM_NAME: der Name der VM.

  • ENCRYPTION_KEY_FILE: der relative Pfad zur JSON-Datei, die den vom Kunden bereitgestellten Verschlüsselungsschlüssel enthält.

  • PROJECT_ID: die Projekt-ID des Projekts, in dem sich die VM befindet.

  • ZONE ist die Zone, in der sich die VM befindet.

Einfach loslegen (Go)

import (
	"context"
	"fmt"
	"io"

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

// startInstanceWithEncKey starts a stopped Google Compute Engine instance (with encrypted disks).
func startInstanceWithEncKey(w io.Writer, projectID, zone, instanceName, key string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// key := "your_encryption_key"

	ctx := context.Background()
	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

	instanceReq := &computepb.GetInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
	}

	instance, err := instancesClient.Get(ctx, instanceReq)
	if err != nil {
		return fmt.Errorf("unable to get instance: %w", err)
	}

	req := &computepb.StartWithEncryptionKeyInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
		InstancesStartWithEncryptionKeyRequestResource: &computepb.InstancesStartWithEncryptionKeyRequest{
			Disks: []*computepb.CustomerEncryptionKeyProtectedDisk{
				{
					Source: proto.String(instance.GetDisks()[0].GetSource()),
					DiskEncryptionKey: &computepb.CustomerEncryptionKey{
						RawKey: proto.String(key),
					},
				},
			},
		},
	}

	op, err := instancesClient.StartWithEncryptionKey(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to start instance with encryption key: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Instance with encryption key started\n")

	return nil
}

Java


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.compute.v1.CustomerEncryptionKey;
import com.google.cloud.compute.v1.CustomerEncryptionKeyProtectedDisk;
import com.google.cloud.compute.v1.GetInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.InstancesStartWithEncryptionKeyRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.StartWithEncryptionKeyInstanceRequest;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class StartEncryptedInstance {

  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 start.
       key: bytes object representing a raw base64 encoded key to your machines boot disk.
            For more information about disk encryption see:
            https://cloud.google.com/compute/docs/disks/customer-supplied-encryption#specifications
     */
    String project = "your-project-id";
    String zone = "zone-name";
    String instanceName = "instance-name";
    String key = "raw-key";

    startEncryptedInstance(project, zone, instanceName, key);
  }

  // Starts a stopped Google Compute Engine instance (with encrypted disks).
  public static void startEncryptedInstance(String project, String zone, String instanceName,
      String key)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    /* Initialize client that will be used to send requests. This client only needs to be created
       once, and can be reused for multiple requests. After completing all of your requests, call
       the `instancesClient.close()` method on the client to safely
       clean up any remaining background resources. */
    try (InstancesClient instancesClient = InstancesClient.create()) {

      GetInstanceRequest getInstanceRequest = GetInstanceRequest.newBuilder()
          .setProject(project)
          .setZone(zone)
          .setInstance(instanceName).build();

      Instance instance = instancesClient.get(getInstanceRequest);

      // Prepare the information about disk encryption.
      CustomerEncryptionKeyProtectedDisk protectedDisk = CustomerEncryptionKeyProtectedDisk
          .newBuilder()
          /* Use raw_key to send over the key to unlock the disk
             To use a key stored in KMS, you need to provide:
             `kms_key_name` and `kms_key_service_account`
           */
          .setDiskEncryptionKey(CustomerEncryptionKey.newBuilder()
              .setRawKey(key).build())
          .setSource(instance.getDisks(0).getSource())
          .build();

      InstancesStartWithEncryptionKeyRequest startWithEncryptionKeyRequest =
          InstancesStartWithEncryptionKeyRequest.newBuilder()
              .addDisks(protectedDisk).build();

      StartWithEncryptionKeyInstanceRequest encryptionKeyInstanceRequest =
          StartWithEncryptionKeyInstanceRequest.newBuilder()
              .setProject(project)
              .setZone(zone)
              .setInstance(instanceName)
              .setInstancesStartWithEncryptionKeyRequestResource(startWithEncryptionKeyRequest)
              .build();

      OperationFuture<Operation, Operation> operation = instancesClient.startWithEncryptionKeyAsync(
          encryptionKeyInstanceRequest);
      Operation response = operation.get(3, TimeUnit.MINUTES);

      if (response.getStatus() == Status.DONE) {
        System.out.println("Encrypted instance started successfully ! ");
      }
    }
  }

}

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 key = 'YOUR_KEY_STRING'

const compute = require('@google-cloud/compute');

async function startInstanceWithEncryptionKey() {
  const instancesClient = new compute.InstancesClient();

  const [instance] = await instancesClient.get({
    project: projectId,
    zone,
    instance: instanceName,
  });

  const [response] = await instancesClient.startWithEncryptionKey({
    project: projectId,
    zone,
    instance: instanceName,
    instancesStartWithEncryptionKeyRequestResource: {
      disks: [
        {
          source: instance.disks[0].source,
          diskEncryptionKey: {
            rawKey: key,
          },
        },
      ],
    },
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

  // Wait for the operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log('Instance with encryption key started.');
}

startInstanceWithEncryptionKey();

PHP

use Google\Cloud\Compute\V1\Client\InstancesClient;
use Google\Cloud\Compute\V1\CustomerEncryptionKey;
use Google\Cloud\Compute\V1\CustomerEncryptionKeyProtectedDisk;
use Google\Cloud\Compute\V1\GetInstanceRequest;
use Google\Cloud\Compute\V1\InstancesStartWithEncryptionKeyRequest;
use Google\Cloud\Compute\V1\StartWithEncryptionKeyInstanceRequest;

/**
 * Starts a stopped Google Compute Engine instance (with encrypted 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 stop.
 * @param string $key Bytes object representing a raw base64 encoded key to your instance's boot disk.
 *                    For more information about disk encryption see:
 *                    https://cloud.google.com/compute/docs/disks/customer-supplied-encryption#specifications
 *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 * @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
 */
function start_instance_with_encryption_key(
    string $projectId,
    string $zone,
    string $instanceName,
    string $key
) {
    // Initiate the InstancesClient.
    $instancesClient = new InstancesClient();

    // Get data about the instance.
    $request = (new GetInstanceRequest())
        ->setInstance($instanceName)
        ->setProject($projectId)
        ->setZone($zone);
    $instanceData = $instancesClient->get($request);

    // Use `setRawKey` to send over the key to unlock the disk
    // To use a key stored in KMS, you need to use `setKmsKeyName` and `setKmsKeyServiceAccount`
    $customerEncryptionKey = (new CustomerEncryptionKey())
        ->setRawKey($key);

    /** @var \Google\Cloud\Compute\V1\AttachedDisk */
    $disk = $instanceData->getDisks()[0];

    // Prepare the information about disk encryption.
    $diskData = (new CustomerEncryptionKeyProtectedDisk())
        ->setSource($disk->getSource())
        ->setDiskEncryptionKey($customerEncryptionKey);

    // Set request with one disk.
    $instancesStartWithEncryptionKeyRequest = (new InstancesStartWithEncryptionKeyRequest())
        ->setDisks(array($diskData));

    // Start the instance with encrypted disk.
    $request2 = (new StartWithEncryptionKeyInstanceRequest())
        ->setInstance($instanceName)
        ->setInstancesStartWithEncryptionKeyRequestResource($instancesStartWithEncryptionKeyRequest)
        ->setProject($projectId)
        ->setZone($zone);
    $operation = $instancesClient->startWithEncryptionKey($request2);

    // Wait for the operation to complete.
    $operation->pollUntilComplete();
    if ($operation->operationSucceeded()) {
        printf('Instance %s started successfully' . PHP_EOL, $instanceName);
    } else {
        $error = $operation->getError();
        printf('Starting instance failed: %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 start_instance_with_encryption_key(
    project_id: str, zone: str, instance_name: str, key: bytes
) -> None:
    """
    Starts a stopped Google Compute Engine instance (with encrypted 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 your want to start.
        key: bytes object representing a raw base64 encoded key to your machines boot disk.
            For more information about disk encryption see:
            https://cloud.google.com/compute/docs/disks/customer-supplied-encryption#specifications
    """
    instance_client = compute_v1.InstancesClient()

    instance_data = instance_client.get(
        project=project_id, zone=zone, instance=instance_name
    )

    # Prepare the information about disk encryption
    disk_data = compute_v1.CustomerEncryptionKeyProtectedDisk()
    disk_data.source = instance_data.disks[0].source
    disk_data.disk_encryption_key = compute_v1.CustomerEncryptionKey()
    # Use raw_key to send over the key to unlock the disk
    # To use a key stored in KMS, you need to provide `kms_key_name` and `kms_key_service_account`
    disk_data.disk_encryption_key.raw_key = key
    enc_data = compute_v1.InstancesStartWithEncryptionKeyRequest()
    enc_data.disks = [disk_data]

    operation = instance_client.start_with_encryption_key(
        project=project_id,
        zone=zone,
        instance=instance_name,
        instances_start_with_encryption_key_request_resource=enc_data,
    )

    wait_for_extended_operation(operation, "instance start (with encrypted disk)")

REST

Um eine VM neu zu starten, die verschlüsselte Laufwerke verwendet, senden Sie eine POST-Anfrage an die Methode instances.startWithEncryptionKey.

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

{
  "disks": [
    {
      "source": "DISK_URL",
      "diskEncryptionKey": {
        "ENCRYPTION_TYPE": "ENCRYPTION_KEY"
      }
    }
  ]
}

Ersetzen Sie Folgendes:

  • PROJECT_ID: die Projekt-ID des Projekts, in dem sich die VM befindet.

  • ZONE ist die Zone, in der sich die VM befindet.

  • VM_NAME: der Name der VM.

  • DISK_URL: Ressourcen-URL, die dem vollständigen Ressourcennamen des angehängten Laufwerks entspricht und mit einem vom Kunden bereitgestellten Verschlüsselungsschlüssel verschlüsselt ist

  • ENCRYPTION_TYPE: Der Typ der verwendeten Laufwerksverschlüsselung, entweder rawKey, kmsKeyName oder rsaEncryptedKey. Wenn Sie den Typ rsaEncryptedKey verwenden, müssen Sie eine POST-Anfrage an die Beta API anstelle der v1 API senden.

  • ENCRYPTION_KEY: der Verschlüsselungsschlüssel, mit dem die an die VM angehängten nichtflüchtigen Speicher verschlüsselt werden. rawKey- oder rsaEncryptedKey-Schlüssel müssen base64-codiert sein. Informationen zum Vorbereiten eines rsaEncryptedKey-Schlüssels finden Sie unter RSA-Key-Wrapping.

VM zurücksetzen

Das Zurücksetzen einer laufenden VM ist vergleichbar mit dem Zurücksetzen eines Computers, z. B. durch Drücken der Reset-Taste oder Drücken und längeres Halten der Ein/Aus-Taste. Wenn Sie eine VM zurücksetzen, geben Sie der VM keine Zeit, das Gastbetriebssystem ordnungsgemäß herunterzufahren. Infolgedessen können die Dateisysteme des Laufwerks beschädigt werden. Google Cloud empfiehlt, eine VM nur dann zurückzusetzen, wenn das Gastbetriebssystem abgestürzt ist und Sie keine anderen Optionen haben. Wenn Sie eine VM neu initialisieren und ein sauberes Herunterfahren durchführen möchten, finden Sie weitere Informationen unter VM neu starten in diesem Dokument.

Beim Zurücksetzen einer VM geschieht Folgendes:

  • Die VM wird im ursprünglichen Bootstatus mit den ursprünglichen Metadaten, dem Image und den nichtflüchtigen Speichern neu initialisiert.

  • Die VM erzwingt das Löschen des Speicherinhalts der Maschine, es sei denn, Sie sichern die Daten.

  • Der VM-Status bleibt während des Prozesses RUNNING.

Durch das Zurücksetzen einer VM werden keine ihrer VM-Attribute geändert. Die VM behält die sitzungsspezifischen IP-Adressen, statischen externen IP-Adressen, nichtflüchtigen Speicher, lokalen SSD-Laufwerke (falls vorhanden) und den Maschinentyp bei.

Console

So setzen Sie eine oder mehrere laufende VMs zurück:

  1. Rufen Sie in der Google Cloud Console die Seite VM-Instanzen auf.

    Zur Seite „VM-Instanzen“

  2. Wählen Sie die VMs aus, die zurückgesetzt werden sollen.

  3. Klicken Sie auf Zurücksetzen und dann noch einmal auf Zurücksetzen.

gcloud

Um eine ausgeführte VM zurückzusetzen, verwenden Sie den Befehl gcloud compute instances reset.

gcloud compute instances reset VM_NAME \
    --project=PROJECT_ID \
    --zone=ZONE

Ersetzen Sie Folgendes:

  • VM_NAME: der Name der VM.

  • PROJECT_ID: die Projekt-ID des Projekts, in dem sich die VM befindet.

  • ZONE ist die Zone, in der sich die VM befindet.

Einfach loslegen (Go)

import (
	"context"
	"fmt"
	"io"

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

// resetInstance resets a running Google Compute Engine instance (with unencrypted disks).
func resetInstance(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.ResetInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
	}

	op, err := instancesClient.Reset(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to reset 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 reset\n")

	return nil
}

Java


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.ResetInstanceRequest;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ResetInstance {

  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 reset.
     */
    String project = "your-project-id";
    String zone = "zone-name";
    String instanceName = "instance-name";

    resetInstance(project, zone, instanceName);
  }

  // Resets a running Google Compute Engine instance (with unencrypted disks).
  public static void resetInstance(String project, String zone, String instanceName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    /* Initialize client that will be used to send requests. This client only needs to be created
       once, and can be reused for multiple requests. After completing all of your requests, call
       the `instancesClient.close()` method on the client to safely
       clean up any remaining background resources. */
    try (InstancesClient instancesClient = InstancesClient.create()) {

      ResetInstanceRequest resetInstanceRequest = ResetInstanceRequest.newBuilder()
          .setProject(project)
          .setZone(zone)
          .setInstance(instanceName)
          .build();

      OperationFuture<Operation, Operation> operation = instancesClient.resetAsync(
          resetInstanceRequest);
      Operation response = operation.get(3, TimeUnit.MINUTES);

      if (response.getStatus() == Status.DONE) {
        System.out.println("Instance reset successfully ! ");
      }
    }
  }

}

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');

async function resetInstance() {
  const instancesClient = new compute.InstancesClient();

  const [response] = await instancesClient.reset({
    project: projectId,
    zone,
    instance: instanceName,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

  // Wait for the operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log('Instance reset.');
}

resetInstance();

PHP

use Google\Cloud\Compute\V1\Client\InstancesClient;
use Google\Cloud\Compute\V1\ResetInstanceRequest;

/**
 * Reset a running 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 reset.
  *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 * @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
 */
function reset_instance(
    string $projectId,
    string $zone,
    string $instanceName
) {
    // Stop the Compute Engine instance using InstancesClient.
    $instancesClient = new InstancesClient();
    $request = (new ResetInstanceRequest())
        ->setInstance($instanceName)
        ->setProject($projectId)
        ->setZone($zone);
    $operation = $instancesClient->reset($request);

    // Wait for the operation to complete.
    $operation->pollUntilComplete();
    if ($operation->operationSucceeded()) {
        printf('Instance %s reset successfully' . PHP_EOL, $instanceName);
    } else {
        $error = $operation->getError();
        printf('Failed to reset 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 reset_instance(project_id: str, zone: str, instance_name: str) -> None:
    """
    Resets a stopped 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 your want to reset.
    """
    instance_client = compute_v1.InstancesClient()

    operation = instance_client.reset(
        project=project_id, zone=zone, instance=instance_name
    )

    wait_for_extended_operation(operation, "instance reset")

REST

Senden Sie zum Zurücksetzen einer ausgeführten VM eine POST-Anfrage an die Methode instances.reset.

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

Ersetzen Sie Folgendes:

  • VM_NAME: der Name der VM.

  • PROJECT_ID: die Projekt-ID des Projekts, in dem sich die VM befindet.

  • ZONE ist die Zone, in der sich die VM befindet.

VM neu starten

Wenn Sie eine VM innerhalb des Gastbetriebssystems neu starten, geschieht Folgendes:

  • Die VM wird im ursprünglichen Bootstatus mit den ursprünglichen Metadaten, dem Image und den nichtflüchtigen Speichern neu initialisiert.

  • Die VM löscht den Speicherinhalt der Maschine, sofern Sie die Daten nicht sichern.

  • Der VM-Status bleibt während des Prozesses RUNNING.

Im Vergleich zum Zurücksetzen einer VM wird beim Neustart einer VM innerhalb des Gastbetriebssystems gewartet, bis die VM alle laufenden Aufgaben beendet hat, bevor das ACPI-Shutdown-Signal an die VM gesendet wird. Dadurch kann die VM ordnungsgemäß heruntergefahren werden.

Durch den Neustart einer VM werden keine ihrer VM-Attribute geändert. Die VM behält die sitzungsspezifischen IP-Adressen, statischen externen IP-Adressen, nichtflüchtigen Speicher, lokalen SSD-Laufwerke (falls vorhanden) und den Maschinentyp bei.

Linux

Um eine Linux-VM zurückzusetzen, starten Sie das Gastbetriebssystem mit dem folgenden Befehl neu:

sudo reboot

Windows

Um eine Windows-VM zurückzusetzen, starten Sie das Gastbetriebssystem mit dem folgenden Befehl neu:

shutdown /r /t 0

Optional können Sie das Windows-Start-Manager-Menü aktivieren, um das Herunterfahren und Neustarten der VM zu überwachen.

Abrechnung

Nachdem eine VM angehalten wurde und Compute Engine den Status auf TERMINATED gesetzt hat, fallen keine Gebühren für die CPU-Nutzung mehr an. Es fallen jedoch weiterhin Gebühren für alle an die VM angehängten Ressourcen an, z. B. nichtflüchtige Speicher und externe IP-Adressen.

Führen Sie einen der folgenden Schritte aus, um Gebühren für die an eine VM angehängten Ressourcen zu vermeiden:

  • Trennen Sie diese Ressourcen von der beendeten VM.

  • Löschen Sie die VM. Diese Aktion löscht auch alle Ressourcen, die an die VM angehängt sind.

Nächste Schritte