Compute Engine-Instanz beenden oder neu starten


In diesem Dokument wird beschrieben, wie Sie eine Compute Engine-Instanz beenden oder neu starten. Weitere Informationen zum Anhalten, Beenden oder Zurücksetzen einer Instanz finden Sie unter Compute Engine-Instanzen anhalten, beenden oder zurücksetzen.

Das Anhalten einer Instanz ist nützlich, wenn Sie sie nicht mehr verwenden oder ihre Eigenschaften ändern möchten, z. B. den Maschinentyp ändern oder angehängte und bereitgestellte Laufwerke entfernen möchten. Nachdem Sie die Instanz beendet haben, können Sie Folgendes tun:

  • Starten Sie sie neu, um Ihre Arbeitslast fortzusetzen.

  • Löschen Sie sie, wenn Sie sie nicht mehr benötigen.

Wenn Sie das Beenden oder Neustarten einer Instanz automatisieren möchten, lesen Sie stattdessen die folgenden Informationen:

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 so bei Compute Engine authentifizieren.
    <x0A>

    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. After installing the Google Cloud CLI, initialize it by running the following command:

        gcloud init

        If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

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

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

        1. Install the Google Cloud CLI.

        2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

        3. To initialize the gcloud CLI, run the following command:

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

          If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

        Weitere Informationen unter Set up authentication for a local development environment.

        Java

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

        1. Install the Google Cloud CLI.

        2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

        3. To initialize the gcloud CLI, run the following command:

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

          If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

        Weitere Informationen unter Set up authentication for a local development environment.

        Node.js

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

        1. Install the Google Cloud CLI.

        2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

        3. To initialize the gcloud CLI, run the following command:

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

          If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

        Weitere Informationen unter Set up authentication for a local development environment.

        PHP

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

        1. Install the Google Cloud CLI.

        2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

        3. To initialize the gcloud CLI, run the following command:

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

          If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

        Weitere Informationen unter Set up authentication for a local development environment.

        Python

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

        1. Install the Google Cloud CLI.

        2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

        3. To initialize the gcloud CLI, run the following command:

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

          If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

        Weitere Informationen unter Set up authentication for a local development environment.

        REST

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

          After installing the Google Cloud CLI, initialize it by running the following command:

          gcloud init

          If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

        Weitere Informationen finden Sie in der Dokumentation zur Google Cloud -Authentifizierung unter Für die Verwendung von REST authentifizieren.

Erforderliche Rollen

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

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

Erforderliche Berechtigungen

Die folgenden Berechtigungen sind erforderlich, um eine Compute-Instanz zu stoppen oder neu zu starten:

  • So beenden Sie eine Instanz: compute.instances.stop für die Instanz
  • So beenden Sie eine Instanz über das Gastbetriebssystem: compute.instances.setMetadata für die Instanz, wenn sie öffentliche SSH-Schlüssel auf Instanzebene verwendet.
  • So starten Sie eine Instanz neu: compute.instances.start für die Instanz
  • So starten Sie eine Instanz neu, die Verschlüsselungsschlüssel verwendet: compute.instances.startWithEncryptionKey auf der Instanz

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

Instanz beenden

Wenn Sie eine Compute-Instanz beenden oder Compute Engine dies im Rahmen einer geplanten Aktion tut, behält die Instanz ihre angehängten Ressourcen, Konfigurationseinstellungen, internen IP-Adressen, MAC-Adressen und Metadaten bei. Die Instanz verliert jedoch ihre Daten im Arbeitsspeicher und ihren Anwendungsstatus. Wenn Sie diese Status beibehalten möchten, halten Sie stattdessen die Instanz an.

Sie können eine Instanz mit den folgenden Methoden beenden. Das hängt davon ab, ob die Instanz lokale SSD-Laufwerke hat und wie Sie Herunterfahrskripts verarbeiten möchten:

  • Instanz ohne lokale SSDs beenden

    Sie können eine oder mehrere Instanzen gleichzeitig anhalten, an die keine lokalen SSDs angehängt sind. Alle Shutdown-Skripts in einer Instanz müssen innerhalb des Standard-Shutdown-Zeitraums abgeschlossen werden.

  • Instanz mit lokalen SSDs beenden

    Wenn Sie eine oder mehrere Instanzen mit angehängten lokalen SSD-Laufwerken gleichzeitig beenden, können Sie auswählen, ob die Daten auf diesen Laufwerken verworfen oder beibehalten werden sollen (Vorabversion). Alle Shutdown-Skripts in der Instanz müssen innerhalb des standardmäßigen Shutdown-Zeitraums abgeschlossen werden.

  • Instanz über das Gastbetriebssystem beenden

    Mit diesem Ansatz können Sie eine einzelne Instanz erst beenden, nachdem Ihre Shutdown-Skripts ausgeführt wurden. Wenn Sie Graceful Shutdown aktiviert haben, können Sie die Instanz beenden, ohne sie ordnungsgemäß herunterzufahren, oder ein laufendes Graceful Shutdown beenden. Wenn Sie Daten von angehängten lokalen SSD-Laufwerken nicht manuell auf einem dauerhaften Speichervolume sichern, werden alle Daten auf diesen Laufwerken verworfen, wenn Sie eine Instanz über das Gastbetriebssystem beenden.

Instanz ohne lokale SSDs beenden

Je nachdem, was Sie beim Beenden einer Instanz tun möchten, haben Sie folgende Möglichkeiten:

  • Wenn Sie das ordnungsgemäße Herunterfahren in der Instanz aktiviert haben, können Sie die Instanz über die Google Cloud Console, die gcloud CLI oder die REST API beenden, ohne sie ordnungsgemäß herunterzufahren, oder ein laufendes ordnungsgemäßes Herunterfahren beenden.

  • Wenn Sie mehrere Instanzen gleichzeitig beenden möchten, verwenden Sie die Google Cloud Console oder, für Instanzen in derselben Zone, die gcloud CLI.

Wählen Sie eine der folgenden Optionen aus, um eine oder mehrere Instanzen zu beenden:

Console

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

    Zu „VM-Instanzen“

  2. Wählen Sie die laufenden Instanzen aus, die Sie beenden möchten.

  3. Klicken Sie auf Beenden. Wenn die Option Beenden nicht angezeigt wird, klicken Sie auf  Weitere Aktionen > Beenden.

  4. Gehen Sie im Dialogfeld so vor:

    1. Optional: Wenn Sie die Instanzen beenden möchten, ohne sie ordnungsgemäß herunterzufahren, oder ein laufendes ordnungsgemäßes Herunterfahren beenden möchten, wählen Sie das Kästchen Ordnungsgemäßes Herunterfahren überspringen (falls zutreffend) aus.

    2. Klicken Sie zur Bestätigung auf Beenden.

gcloud

Wenn Sie eine oder mehrere Instanzen in derselben Zone beenden möchten, verwenden Sie den Befehl gcloud compute instances stop:

gcloud compute instances stop INSTANCE_NAMES \
    --zone=ZONE

Ersetzen Sie Folgendes:

  • INSTANCE_NAMES: eine Liste von Instanznamen, die durch Leerzeichen getrennt sind, z. B. instance-01 instance-02 instance-03.

  • ZONE: die Zone, in der sich die Instanzen befinden.

Wenn Sie in einer oder mehreren Instanzen das ordnungsgemäße Herunterfahren aktiviert haben, können Sie die Instanzen optional anhalten, ohne sie ordnungsgemäß herunterzufahren, oder ein laufendes ordnungsgemäßes Herunterfahren manuell beenden. Führen Sie dazu den Befehl gcloud beta compute instances stop mit dem Flag --no-graceful-shutdown aus:

gcloud beta compute instances stop INSTANCE_NAMES \
    --no-graceful-shutdown \
    --zone=ZONE

Go

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
)

// 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.Error&f("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(&quot;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)
          .b<uild();

      Opera>tionFutureOperation, 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 = $op>eration-getError();
        printf('Failed to stop instance: %s' . P>HP_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)

    ret>urn 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 Instanz eine POST-Anfrage an die Methode instances.stop:

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

Ersetzen Sie Folgendes:

  • INSTANCE_NAME: der Name der Instanz.

  • PROJECT_ID: die ID des Projekts, in dem sich die Instanz befindet.

  • ZONE: die Zone, in der sich die Instanz befindet.

Wenn Sie das ordnungsgemäße Herunterfahren in einer Instanz aktiviert haben, können Sie die Instanz optional beenden, ohne sie ordnungsgemäß herunterzufahren, oder ein laufendes ordnungsgemäßes Herunterfahren manuell beenden. Stellen Sie dazu eine POST-Anfrage an die Methode instances.stop. Fügen Sie in der Anfrage-URL den Abfrageparameter noGracefulShutdown=true ein:

POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/stop?noGracefulShutdown=true

Instanz mit lokalen SSD-Laufwerken beenden

Je nachdem, was Sie beim Beenden einer Compute-Instanz tun möchten, haben Sie folgende Möglichkeiten:

  • Wenn Sie das ordnungsgemäße Herunterfahren in der Instanz aktiviert haben, können Sie die Instanz über die Google Cloud Console, die gcloud CLI oder die REST API beenden, ohne sie ordnungsgemäß herunterzufahren, oder ein laufendes ordnungsgemäßes Herunterfahren beenden.

  • Wenn Sie die Daten der an eine Instanz angehängten lokalen SSD-Laufwerke beibehalten möchten (mit Ausnahme von Maschinentypen, die Titanium-SSDs verwenden), beenden Sie die Instanz mit der gcloud CLI oder der REST API.

  • Wenn Sie mehrere Instanzen gleichzeitig beenden möchten, verwenden Sie die Google Cloud Console oder, für Instanzen in derselben Zone, die gcloud CLI.

Wenn Sie eine oder mehrere Instanzen mit angehängten lokalen SSD-Laufwerken beenden möchten, wählen Sie eine der folgenden Optionen aus:

Console

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

    Zu „VM-Instanzen“

  2. Wählen Sie die laufenden Instanzen aus, die Sie beenden möchten.

  3. Klicken Sie auf Beenden. Wenn die Option Beenden nicht angezeigt wird, klicken Sie auf  Weitere Aktionen > Beenden.

  4. Gehen Sie im Dialogfeld so vor:

    1. Optional: Wenn Sie die Instanzen beenden möchten, ohne sie ordnungsgemäß herunterzufahren, oder ein laufendes ordnungsgemäßes Herunterfahren beenden möchten, wählen Sie das Kästchen Ordnungsgemäßes Herunterfahren überspringen (falls zutreffend) aus.

    2. Klicken Sie zur Bestätigung auf Beenden.

gcloud

Wenn Sie eine oder mehrere Instanzen in derselben Zone mit angehängten lokalen SSD-Laufwerken beenden, geben Sie an, ob die lokalen SSD-Daten verworfen oder beibehalten werden sollen:

Ersetzen Sie Folgendes:

  • INSTANCE_NAMES: eine Liste von Instanznamen, die durch Leerzeichen getrennt sind, z. B. instance-01 instance-02 instance-03.

  • ZONE: die Zone, in der sich die Instanzen befinden.

Wenn Sie in einer oder mehreren Instanzen die ordnungsgemäße Beendigung aktiviert haben, können Sie die Instanzen optional beenden, ohne sie ordnungsgemäß herunterzufahren, oder eine laufende ordnungsgemäße Beendigung beenden. Führen Sie dazu den Befehl gcloud beta compute instances stop mit dem Flag --no-graceful-shutdown aus:

gcloud beta compute instances stop INSTANCE_NAMES \
    --discard-local-ssd=DISCARD_LOCAL_SSD \
    --no-graceful-shutdown \
    --zone=ZONE

Ersetzen Sie DISCARD_LOCAL_SSD durch true, um die Daten auf den lokalen SSD-Festplatten zu verwerfen, oder durch false, um die Daten beizubehalten.

REST

Wenn Sie eine Instanz mit angehängten lokalen SSDs beenden, geben Sie an, ob die lokalen SSD-Daten verworfen oder beibehalten werden sollen:

  • Senden Sie eine POST-Anfrage an die Methode instances.stop, um lokale SSD-Daten zu verwerfen. Fügen Sie in der Anfrage-URL den Abfrageparameter discardLocalSsd ein, wobei dieser auf true gesetzt ist:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/stop?discardLocalSsd=true
    
  • Wenn Sie Daten auf der lokalen SSD beibehalten möchten, stellen Sie eine POST-Anfrage an die Methode beta.instances.stop. Fügen Sie in der Anfrage-URL den Abfrageparameter discardLocalSsd ein, wobei dieser auf false gesetzt ist:

    POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/stop?discardLocalSsd=false
    

Ersetzen Sie Folgendes:

  • PROJECT_ID: die ID des Projekts, in dem sich die Instanz befindet.

  • ZONE: die Zone, in der sich die Instanz befindet.

  • INSTANCE_NAME: der Name der Instanz.

Wenn Sie das ordnungsgemäße Herunterfahren in einer Instanz aktiviert haben, können Sie die Instanz optional beenden, ohne sie ordnungsgemäß herunterzufahren, oder ein laufendes ordnungsgemäßes Herunterfahren manuell beenden. Stellen Sie dazu eine POST-Anfrage an die Methode instances.stop. Fügen Sie in der Anfrage-URL den Abfrageparameter noGracefulShutdown=true ein:

POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/stop?discardLocalSsd=DISCARD_LOCAL_SSD&noGracefulShutdown=true

Ersetzen Sie DISCARD_LOCAL_SSD durch true, um die Daten auf den lokalen SSD-Festplatten zu verwerfen, oder durch false, um die Daten beizubehalten.

Instanz über das Gastbetriebssystem beenden

Wenn an eine Compute-Instanz lokale SSD-Laufwerke angehängt sind, werden die lokalen SSD-Daten automatisch verworfen, wenn das Gastbetriebssystem heruntergefahren wird. Wenn Sie diese Daten beibehalten möchten, kopieren Sie sie manuell in eine Option für nichtflüchtigen Speicher, bevor Sie die Instanz beenden.

Wählen Sie eine der folgenden Optionen aus, um eine Instanz über das Gastbetriebssystem zu beenden:

Linux

  1. Stellen Sie eine Verbindung zur Instanz her, falls Sie dies noch nicht getan haben.

  2. Wählen Sie eine der folgenden Methoden aus, um die Instanz zu beenden:

    • Führen Sie den folgenden Befehl aus, um ein ordnungsgemäßes Herunterfahren zu erzwingen, bei dem die Instanz Herunterfahrskripts ausführen kann, bevor das Gastbetriebssystem heruntergefahren wird:

      sudo shutdown -h now
      
    • Andernfalls führen Sie den folgenden Befehl aus, um ein Herunterfahren zu erzwingen:

      sudo poweroff
      

Windows

  1. Wenn Sie noch keine Verbindung zur Instanz hergestellt haben, verwenden Sie eine der folgenden Methoden:

  2. Wählen Sie eine der folgenden Methoden aus, um die Instanz zu beenden:

    • Führen Sie den folgenden Befehl aus, um die Instanz ordnungsgemäß zu beenden und die Instanz vor dem Herunterfahren des Gastbetriebssystems Herunterfahrskripts ausführen zu lassen:

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

      shutdown /f
      

Instanz neu starten

Sie können eine Compute-Instanz neu starten, die vollständig beendet wurde. Der Instanzstatus ist dann TERMINATED.

Wenn Sie beim Beenden der Instanz die Daten Ihrer lokalen SSD-Laufwerke beibehalten haben, müssen Sie die lokalen SSD-Laufwerke nach dem Neustart möglicherweise neu einbinden. Weitere Informationen zum Bereitstellen lokaler SSD-Laufwerke finden Sie unter Lokales SSD-Gerät formatieren und bereitstellen.

Verwenden Sie eine der folgenden Methoden, um eine Instanz neu zu starten. Die Methode hängt davon ab, ob an die Instanz verschlüsselte Laufwerke angehängt sind:

Instanz ohne verschlüsselte Laufwerke neu starten

Sie können mehrere Compute-Instanzen gleichzeitig oder einzelne Instanzen neu starten. Verwenden Sie für mehrere Instanzen die Google Cloud Konsole oder, für Instanzen in derselben Zone, die gcloud CLI. Wählen Sie für einzelne Instanzen eine der folgenden Optionen aus:

Console

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

    Zu „VM-Instanzen“

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

  3. Klicken Sie auf Starten/Fortsetzen.

gcloud

Wenn Sie eine oder mehrere Instanzen in derselben Zone neu starten möchten, verwenden Sie den gcloud compute instances start-Befehl:

gcloud compute instances start INSTANCE_NAMES \
    --zone=ZONE

Ersetzen Sie Folgendes:

  • INSTANCE_NAMES: eine Liste von Instanznamen, die durch Leerzeichen getrennt sind, z. B. instance-01 instance-02 instance-03.

  • ZONE: die Zone, in der sich die Instanzen befinden.

Go

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
)

// 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.Error&f("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(&quot;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)
          .b<uild();

      Opera>tionFutureOperation, 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 = $op>eration-getError();
        printf('Failed to start instance: %s' . P>HP_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)

    retu>rn 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 Neustarten einer Instanz eine POST-Anfrage an die Methode instances.start:

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

Ersetzen Sie Folgendes:

  • INSTANCE_NAME: der Name der Instanz, die neu gestartet werden soll.

  • PROJECT_ID: die ID des Projekts, in dem sich die Instanz befindet.

  • ZONE: die Zone, in der sich die Instanz befindet.

Instanz mit verschlüsselten Laufwerken neu starten

Wenn Sie eine angehaltene Compute-Instanz neu starten, an die Laufwerke angehängt sind, die mit vom Kunden bereitgestellten Verschlüsselungsschlüsseln verschlüsselt wurden, müssen Sie die Informationen zum Verschlüsselungsschlüssel angeben.

Sie können mehrere Instanzen gleichzeitig oder einzelne Instanzen neu starten. Bei mehreren Instanzen verwenden Sie die Google Cloud Console oder, für Instanzen in derselben Zone, die gcloud CLI. Wählen Sie für einzelne Instanzen eine der folgenden Optionen aus:

Console

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

    Zu „VM-Instanzen“

  2. Wählen Sie die Instanzen aus, die neu gestartet werden sollen.

  3. Klicken Sie auf Starten/Fortsetzen.

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

gcloud

Wenn Sie eine oder mehrere Instanzen, die verschlüsselte Laufwerke in derselben Zone verwenden, neu starten möchten, verwenden Sie den Befehl gcloud compute instances start mit dem Flag --csek-key-file. Wenn Sie einen mit RSA verpackten Schlüssel verwenden, nutzen Sie stattdessen den Befehl gcloud beta compute instances start mit dem Flag --csek-key-file:

gcloud compute instances start INSTANCE_NAMES \
    --csek-key-file=ENCRYPTION_KEY_FILE \
    --zone=ZONE

Ersetzen Sie Folgendes:

  • INSTANCE_NAMES: eine Liste von Instanznamen, die durch Leerzeichen getrennt sind, z. B. instance-01 instance-02 instance-03.

  • ENCRYPTION_KEY_FILE: der relative Pfad zur JSON-Datei, die den vom Kunden bereitgestellten Verschlüsselungsschlüssel enthält. Sie können mehrere Instanzen nur dann gleichzeitig neu starten, wenn sie denselben vom Kunden bereitgestellten Verschlüsselungsschlüssel verwenden.

  • ZONE: die Zone, in der sich die Instanzen befinden.

Go

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"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 {
		retu&rn fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

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

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

	req := computepb.StartWithEncryptionKeyInstanceReques&t{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
		InstancesStartWithEncryptionKeyRequestResource: computepb.InstancesStartWithEncryptionKeyRequest{
			Disks: []*computepb.CustomerE&ncryptionKeyProtectedDisk{
				{
					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();

 >     OperationFutureOperation, 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 = $instancesCli>ent-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 = $instanceD>ata-getDisks()[0];

    // Prepare the information about disk encryption.
    $diskData = (new CustomerEncryptionKeyProtectedDisk())
     >   -setSource($d>isk-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 = $instancesCli>ent-startWithEncryptionKey($request2);

    // Wait for the operation to complete.
    $operat>ion-pollUntilComplete();
    if ($operat>ion-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_en>cryption_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 Instanz mit verschlüsselten Laufwerken neu zu starten, stellen Sie eine POST-Anfrage an die Methode instances.startWithEncryptionKey:

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

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

Ersetzen Sie Folgendes:

  • PROJECT_ID: die ID des Projekts, in dem sich die Instanz befindet.

  • ZONE: die Zone, in der sich die Instanz befindet.

  • INSTANCE_NAME: der Name der Instanz.

  • 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, die einer der folgenden Werte sein kann: rawKey, kmsKeyName oder rsaEncryptedKey. Wenn Sie den Typ rsaEncryptedKey verwenden, stellen Sie eine POST-Anfrage an die Methode beta.instances.startWithEncryptionKey.

  • ENCRYPTION_KEY: der Verschlüsselungsschlüssel, der zum Verschlüsseln der an die Instanz angehängten nichtflüchtigen Speicher verwendet wird. Schlüssel vom Typ rawKey oder rsaEncryptedKey müssen base64-codiert sein. Informationen zum Vorbereiten eines rsaEncryptedKey-Schlüssels finden Sie unter RSA-Key-Wrapping.

Nächste Schritte