VM aus Instanzvorlage erstellen


Auf dieser Seite wird erläutert, wie Sie eine Instanzvorlage zum Erstellen einer VM-Instanz verwenden. Eine Instanzvorlage ist eine API-Ressource, mit der die Properties von VM-Instanzen definiert werden. In einer Instanzvorlage werden Attribute wie Maschinentyp, Betriebssystem-Image, Konfiguration nichtflüchtiger Speicher, Metadaten, Startskripts usw. definiert. Diese Instanzvorlage kann dann zum Erstellen einzelner VM-Instanzen oder Gruppen von verwalteten Instanzen verwendet werden.

Wenn Sie eine Instanzvorlage zum Erstellen einer VM-Instanz verwenden, wird standardmäßig eine VM-Instanz erstellt, die mit den Properties in der Vorlage identisch ist. Eine Ausnahme bilden der Name der VM-Instanz und die Zone, in der die Instanz ausgeführt wird. Alternativ können Sie bestimmte Felder bei der Instanzerstellung optional überschreiben, wenn Sie bestimmte Properties der Instanzvorlage für bestimmte Verwendungsmöglichkeiten ändern möchten.

In diesem Dokument wird davon ausgegangen, dass Sie bereits über eine einsatzbereite Instanzvorlage verfügen. Wenn Sie keine Instanzvorlage haben, befolgen Sie die Anweisungen zum Erstellen einer neuen Instanzvorlage.

Hinweise

  • Lesen Sie die Dokumentation zu Instanzvorlagen.
  • Erstellen Sie eine Instanzvorlage.
  • 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.

    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

VM-Instanz aus einer Instanzvorlage erstellen

Sie können entweder eine regionale oder eine globale Instanzvorlage verwenden, um eine VM-Instanz zu erstellen. Folgen Sie diesen Anweisungen, um eine Instanz zu erstellen, die mit der Beschreibung in der Instanzvorlage identisch ist.

Console

  1. Rufen Sie in der Google Cloud Console die Seite Instanz erstellen auf.

    Zur Seite „Instanz erstellen“

  2. Klicken Sie auf Neue VM-Instanz aus Vorlage.

  3. Wählen Sie eine Vorlage aus und klicken Sie auf Weiter.

  4. Geben Sie einen Namen für Ihre VM an und nehmen Sie nach Bedarf weitere Anpassungen vor.

  5. Klicken Sie auf Erstellen.

    Weitere Informationen zur Einrichtung finden Sie unter VM-Instanz aus einem Image erstellen.

gcloud

Verwenden Sie zum Erstellen einer VM aus einer regionalen oder globalen Instanzvorlage denselben Befehl gcloud compute instances create, den Sie auch zum Erstellen einer normalen Instanz verwenden würden, aber Fügen Sie --source-instance-template-Flag hinzu:

gcloud compute instances create VM_NAME \
    --source-instance-template INSTANCE_TEMPLATE_NAME

Ersetzen Sie Folgendes:

  • VM_NAME: Der Name der Instanz.
  • INSTANCE_TEMPLATE_NAME: Name der zu verwendenden Instanzvorlage. Bei einer regionalen Instanzvorlage müssen Sie die URL der Vorlage vollständig oder teilweise angeben. Ein Beispiel für eine vollständige URL ist https://www.googleapis.com/compute/v1/projects/example-project/regions/us-central1/instanceTemplates/example-regional-instance-template und für eine teilweise URL projects/example-project/regions/us-central1/instanceTemplates/example-regional-instance-template.

Beispiel:

gcloud compute instances create example-instance \
    --source-instance-template my-instance-template

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"
)

// createInstanceFromTemplate creates a Compute Engine VM instance from an instance template.
func createInstanceFromTemplate(w io.Writer, projectID, zone, instanceName, instanceTemplateUrl string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// instanceTemplateUrl := "global/instanceTemplates/your_instance_template"

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

	req := &computepb.InsertInstanceRequest{
		Project: projectID,
		Zone:    zone,
		InstanceResource: &computepb.Instance{
			Name: proto.String(instanceName),
		},
		SourceInstanceTemplate: &instanceTemplateUrl,
	}

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

	return nil
}

Java


import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.InsertInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstanceProperties;
import com.google.cloud.compute.v1.InstanceTemplate;
import com.google.cloud.compute.v1.InstanceTemplatesClient;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateInstanceFromTemplate {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    /*  TODO(developer): Replace these variables before running the sample.
        projectId - ID or number of the project you want to use.
        zone - Name of the zone you want to check, for example: us-west3-b
        instanceName - Name of the new instance.
        instanceTemplateURL - URL of the instance template using for creating the new instance.
        It can be a full or partial URL.
        Examples:
        - https://www.googleapis.com/compute/v1/projects/project/global/instanceTemplates/example-instance-template
        - projects/project/global/instanceTemplates/example-instance-template
        - global/instanceTemplates/example-instance-template
     */
    String projectId = "your-project-id";
    String zone = "zone-name";
    String instanceName = "instance-name";
    String instanceTemplateUrl = "instance-template-url";
    createInstanceFromTemplate(projectId, zone, instanceName, instanceTemplateUrl);
  }

  // Create a new instance from template in the specified project and zone.
  public static void createInstanceFromTemplate(String projectId, String zone, String instanceName,
      String instanceTemplateName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    try (InstancesClient instancesClient = InstancesClient.create();
        InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create()) {

      InstanceTemplate instanceTemplate = instanceTemplatesClient.get(projectId,
          instanceTemplateName);

      // Adjust diskType field of the instance template to use the URL formatting
      // required by instances.insert.diskType
      // For instance template, there is only a name, not URL.
      List<AttachedDisk> reformattedAttachedDisks = new ArrayList<>();
      for (AttachedDisk disk : instanceTemplate.getProperties().getDisksList()) {
        disk = AttachedDisk.newBuilder(disk)
            .setInitializeParams(AttachedDiskInitializeParams
                .newBuilder(disk.getInitializeParams())
                .setDiskType(
                    String.format(
                        "zones/%s/diskTypes/%s", zone, disk.getInitializeParams().getDiskType()))
                .build())
            .build();

        reformattedAttachedDisks.add(disk);
      }

      // Clear existing disks and set the reformatted disks in the instance template.
      instanceTemplate = InstanceTemplate
          .newBuilder(instanceTemplate)
          .setProperties(InstanceProperties
              .newBuilder(instanceTemplate.getProperties())
              .clearDisks()
              .addAllDisks(reformattedAttachedDisks)
              .build())
          .build();

      InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setInstanceResource(Instance.newBuilder().setName(instanceName).build())
          .setSourceInstanceTemplate(instanceTemplate.getSelfLink()).build();

      Operation response = instancesClient.insertAsync(insertInstanceRequest)
          .get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        System.out.println("Instance creation from template failed ! ! " + response);
        return;
      }
      System.out
          .printf("Instance creation from template: Operation Status %s: %s ", instanceName,
              response.getStatus());
    }
  }
}

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 instanceTemplateUrl = 'YOUR_INSTANCE_TEMPLATE_URL'

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

// Create a new instance from template in the specified project and zone.
async function createInstanceFromTemplate() {
  const instancesClient = new compute.InstancesClient();

  console.log(
    `Creating the ${instanceName} instance in ${zone} from template ${instanceTemplateUrl}...`
  );

  const [response] = await instancesClient.insert({
    project: projectId,
    zone,
    instanceResource: {
      name: instanceName,
    },
    sourceInstanceTemplate: instanceTemplateUrl,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

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

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

createInstanceFromTemplate();

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 create_instance_from_template(
    project_id: str, zone: str, instance_name: str, instance_template_url: str
) -> compute_v1.Instance:
    """
    Creates a Compute Engine VM instance from an instance template.

    Args:
        project_id: ID or number of the project you want to use.
        zone: Name of the zone you want to check, for example: us-west3-b
        instance_name: Name of the new instance.
        instance_template_url: URL of the instance template used for creating the new instance.
            It can be a full or partial URL.
            Examples:
            - https://www.googleapis.com/compute/v1/projects/project/global/instanceTemplates/example-instance-template
            - projects/project/global/instanceTemplates/example-instance-template
            - global/instanceTemplates/example-instance-template

    Returns:
        Instance object.
    """
    instance_client = compute_v1.InstancesClient()

    instance_insert_request = compute_v1.InsertInstanceRequest()
    instance_insert_request.project = project_id
    instance_insert_request.zone = zone
    instance_insert_request.source_instance_template = instance_template_url
    instance_insert_request.instance_resource.name = instance_name

    operation = instance_client.insert(instance_insert_request)
    wait_for_extended_operation(operation, "instance creation")

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

REST

Wenn Sie eine VM aus einer regionalen oder globalen Instanzvorlage erstellen möchten, erstellen Sie eine normale Anfrage zum Erstellen einer Instanz, fügen Sie jedoch das sourceInstanceTemplate-Abfrageparameter hinzu gefolgt von einem qualifizierten Pfad zu einer Instanzvorlage.

POST https://compute.googleapis.com/compute/v1/projects/
PROJECT_ID/zones/ZONE/
instances?sourceInstanceTemplate=INSTANCE_TEMPLATE_NAME

Geben Sie im Anfragetext einen name für die VM-Instanz an:

{ "name": "example-instance" }

Das folgende Snippet enthält beispielsweise einen vollständig qualifizierten Pfad zur Vorlage: https://compute.googleapis.com/compute/v1/projects/myproject/global/instanceTemplates/example-instance-template.

POST https://compute.googleapis.com/
compute/v1/projects/myproject/zones/us-central1-a/instances?sourceInstanceTemplate=
https://compute.googleapis.com/compute/v1/projects/myproject/global/
instanceTemplates/example-instance-template
{ "name": "example-instance" }

VM-Instanz aus einer Instanzvorlage mit Überschreibungen erstellen

Wenn Sie eine VM-Instanz aus einer Instanzvorlage erstellen, wird standardmäßig eine VM-Instanz erstellt, die mit den Properties in der Vorlage identisch ist. Eine Ausnahme bilden der Name der VM-Instanz und die Zone.

Wenn Sie eine Instanz basierend auf einer Instanzvorlage, jedoch mit einigen Änderungen erstellen möchten, können Sie das Überschreibungsverhalten verwenden. In diesem Zusammenhang legen Sie Attribute fest, die beim Erstellen der Instanz für die vorhandene Instanzvorlage überschrieben werden sollen.

gcloud

Stellen Sie mithilfe der gcloud CLI eine Anfrage zum Erstellen einer Instanz mit dem Flag --source-instance-template und zum Überschreiben eines beliebigen Attributs mit dem entsprechenden Flag gcloud. Eine Liste der anwendbaren Flags finden Sie in der Referenz zu gcloud.

Geben Sie beispielsweise die folgenden Flags an, um den Maschinentyp, Metadaten, das Betriebssystem, das Persistent Disk-Bootlaufwerk und ein sekundäres Laufwerk einer Instanzvorlage zu überschreiben:

gcloud compute instances create example-instance \
    --source-instance-template example-instance --machine-type e2-standard-2 \
    --image-family debian-9 --image-project debian-cloud \
    --metadata bread=butter --disk=boot=no,name=my-override-disk

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"
)

// createInstanceFromTemplate creates a Compute Engine VM instance from an instance template, but overrides the disk and machine type options in the template.
func createInstanceFromTemplateWithOverrides(w io.Writer, projectID, zone, instanceName, instanceTemplateName, machineType, newDiskSourceImage string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// instanceTemplateName := "your_instance_template_name"
	// machineType := "n1-standard-2"
	// newDiskSourceImage := "projects/debian-cloud/global/images/family/debian-10"

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

	intanceTemplatesClient, err := compute.NewInstanceTemplatesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstanceTemplatesRESTClient: %w", err)
	}
	defer intanceTemplatesClient.Close()

	// Retrieve an instance template by name.
	reqGetTemplate := &computepb.GetInstanceTemplateRequest{
		Project:          projectID,
		InstanceTemplate: instanceTemplateName,
	}

	instanceTemplate, err := intanceTemplatesClient.Get(ctx, reqGetTemplate)
	if err != nil {
		return fmt.Errorf("unable to get intance template: %w", err)
	}

	fmt.Printf("%s", "asdfadf")

	for _, disk := range instanceTemplate.Properties.Disks {
		diskType := disk.InitializeParams.GetDiskType()
		if diskType != "" {
			disk.InitializeParams.DiskType = proto.String(fmt.Sprintf(`zones/%s/diskTypes/%s`, zone, diskType))
		}
	}

	reqInsertInstance := &computepb.InsertInstanceRequest{
		Project: projectID,
		Zone:    zone,
		InstanceResource: &computepb.Instance{
			Name:        proto.String(instanceName),
			MachineType: proto.String(fmt.Sprintf(`zones/%s/machineTypes/%s`, zone, machineType)),
			Disks: append(
				// If you override a repeated field, all repeated values
				// for that property are replaced with the
				// corresponding values provided in the request.
				// When adding a new disk to existing disks,
				// insert all existing disks as well.
				instanceTemplate.Properties.Disks,
				&computepb.AttachedDisk{
					InitializeParams: &computepb.AttachedDiskInitializeParams{
						DiskSizeGb:  proto.Int64(10),
						SourceImage: &newDiskSourceImage,
					},
					AutoDelete: proto.Bool(true),
					Boot:       proto.Bool(false),
					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
				},
			),
		},
		SourceInstanceTemplate: instanceTemplate.SelfLink,
	}

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

	return nil
}

Java


import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.InsertInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstanceTemplate;
import com.google.cloud.compute.v1.InstanceTemplatesClient;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateInstanceFromTemplateWithOverrides {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    /* TODO(developer): Replace these variables before running the sample.
     * projectId - ID or number of the project you want to use.
     * zone - Name of the zone you want to check, for example: us-west3-b
     * instanceName - Name of the new instance.
     * instanceTemplateName - Name of the instance template to use when creating the new instance.
     * machineType - Machine type you want to set in following format:
     *    "zones/{zone}/machineTypes/{type_name}". For example:
     *    "zones/europe-west3-c/machineTypes/f1-micro"
     *    You can find the list of available machine types using:
     *    https://cloud.google.com/sdk/gcloud/reference/compute/machine-types/list
     * newDiskSourceImage - Path the the disk image you want to use for your new
     *    disk. This can be one of the public images
     *    (like "projects/debian-cloud/global/images/family/debian-10")
     *    or a private image you have access to.
     *    You can check the list of available public images using the doc:
     *    http://cloud.google.com/compute/docs/images
     */
    String projectId = "your-project-id";
    String zone = "zone-name";
    String instanceName = "instance-name";
    String instanceTemplateName = "instance-template-name";

    createInstanceFromTemplateWithOverrides(projectId, zone, instanceName, instanceTemplateName);
  }

  // Creates a Compute Engine VM instance from an instance template,
  // but overrides the disk and machine type options in the template.
  public static void createInstanceFromTemplateWithOverrides(String projectId, String zone,
      String instanceName, String instanceTemplateName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    try (InstancesClient instancesClient = InstancesClient.create();
        InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create()) {

      String machineType = "n1-standard-1";
      String newDiskSourceImage = "projects/debian-cloud/global/images/family/debian-10";

      // Retrieve an instance template.
      InstanceTemplate instanceTemplate = instanceTemplatesClient
          .get(projectId, instanceTemplateName);

      // Adjust diskType field of the instance template to use the URL formatting
      // required by instances.insert.diskType
      // For instance template, there is only a name, not URL.
      List<AttachedDisk> reformattedAttachedDisks = new ArrayList<>();
      for (AttachedDisk disk : instanceTemplate.getProperties().getDisksList()) {
        disk = AttachedDisk.newBuilder(disk)
            .setInitializeParams(AttachedDiskInitializeParams
                .newBuilder(disk.getInitializeParams())
                .setDiskType(
                    String.format(
                        "zones/%s/diskTypes/%s", zone, disk.getInitializeParams().getDiskType()))
                .build())
            .build();

        reformattedAttachedDisks.add(disk);
      }

      AttachedDisk newdisk = AttachedDisk.newBuilder()
          .setInitializeParams(AttachedDiskInitializeParams.newBuilder()
              .setDiskSizeGb(10)
              .setSourceImage(newDiskSourceImage).build())
          .setAutoDelete(true)
          .setBoot(false)
          .setType(AttachedDisk.Type.PERSISTENT.toString()).build();

      Instance instance = Instance.newBuilder()
          .setName(instanceName)
          .setMachineType(String.format("zones/%s/machineTypes/%s", zone, machineType))
          // If you override a repeated field, all repeated values
          // for that property are replaced with the
          // corresponding values provided in the request.
          // When adding a new disk to existing disks,
          // insert all existing disks as well.
          .addAllDisks(reformattedAttachedDisks)
          .addDisks(newdisk)
          .build();

      InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setInstanceResource(instance)
          .setSourceInstanceTemplate(instanceTemplate.getSelfLink()).build();

      Operation response = instancesClient.insertAsync(insertInstanceRequest)
          .get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        System.out.println("Instance creation from template with overrides failed ! ! " + response);
        return;
      }
      System.out
          .printf("Instance creation from template with overrides: Operation Status %s: %s ",
              instanceName, response.getStatus());
    }

  }
}

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 instanceTemplateName = 'YOUR_INSTANCE_TEMPLATE_NAME';
// const machineType = 'n1-standard-1';
// const newDiskSourceImage = 'projects/debian-cloud/global/images/family/debian-10';

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

// Creates a new instance in the specified project and zone using a selected template,
// but overrides the disk and machine type options in the template.
async function createInstanceFromTemplateWithOverrides() {
  const instancesClient = new compute.InstancesClient();
  const instanceTemplatesClient = new compute.InstanceTemplatesClient();

  console.log(
    `Creating the ${instanceName} instance in ${zone} from template ${instanceTemplateName}...`
  );

  // Retrieve an instance template by name.
  const [instanceTemplate] = await instanceTemplatesClient.get({
    project: projectId,
    instanceTemplate: instanceTemplateName,
  });

  // Adjust diskType field of the instance template to use the URL formatting required by instances.insert.diskType
  // For instance template, there is only a name, not URL.
  for (const disk of instanceTemplate.properties.disks) {
    if (disk.initializeParams.diskType) {
      disk.initializeParams.diskType = `zones/${zone}/diskTypes/${disk.initializeParams.diskType}`;
    }
  }

  const [response] = await instancesClient.insert({
    project: projectId,
    zone,
    instanceResource: {
      name: instanceName,
      machineType: `zones/${zone}/machineTypes/${machineType}`,
      disks: [
        // If you override a repeated field, all repeated values
        // for that property are replaced with the
        // corresponding values provided in the request.
        // When adding a new disk to existing disks,
        // insert all existing disks as well.
        ...instanceTemplate.properties.disks,
        {
          initializeParams: {
            diskSizeGb: '10',
            sourceImage: newDiskSourceImage,
          },
          autoDelete: true,
          boot: false,
          type: 'PERSISTENT',
        },
      ],
    },
    sourceInstanceTemplate: instanceTemplate.selfLink,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

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

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

createInstanceFromTemplateWithOverrides();

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 create_instance_from_template_with_overrides(
    project_id: str,
    zone: str,
    instance_name: str,
    instance_template_name: str,
    machine_type: str,
    new_disk_source_image: str,
) -> compute_v1.Instance:
    """
    Creates a Compute Engine VM instance from an instance template, changing the machine type and
    adding a new disk created from a source image.

    Args:
        project_id: ID or number of the project you want to use.
        zone: Name of the zone you want to check, for example: us-west3-b
        instance_name: Name of the new instance.
        instance_template_name: Name of the instance template used for creating the new instance.
        machine_type: Machine type you want to set in following format:
            "zones/{zone}/machineTypes/{type_name}". For example:
            - "zones/europe-west3-c/machineTypes/f1-micro"
            - You can find the list of available machine types using:
              https://cloud.google.com/sdk/gcloud/reference/compute/machine-types/list
        new_disk_source_image: Path the the disk image you want to use for your new
            disk. This can be one of the public images
            (like "projects/debian-cloud/global/images/family/debian-10")
            or a private image you have access to.
            For a list of available public images, see the documentation:
            http://cloud.google.com/compute/docs/images

    Returns:
        Instance object.
    """
    instance_client = compute_v1.InstancesClient()
    instance_template_client = compute_v1.InstanceTemplatesClient()

    # Retrieve an instance template by name.
    instance_template = instance_template_client.get(
        project=project_id, instance_template=instance_template_name
    )

    # Adjust diskType field of the instance template to use the URL formatting required by instances.insert.diskType
    # For instance template, there is only a name, not URL.
    for disk in instance_template.properties.disks:
        if disk.initialize_params.disk_type:
            disk.initialize_params.disk_type = (
                f"zones/{zone}/diskTypes/{disk.initialize_params.disk_type}"
            )

    instance = compute_v1.Instance()
    instance.name = instance_name
    instance.machine_type = machine_type
    instance.disks = list(instance_template.properties.disks)

    new_disk = compute_v1.AttachedDisk()
    new_disk.initialize_params.disk_size_gb = 50
    new_disk.initialize_params.source_image = new_disk_source_image
    new_disk.auto_delete = True
    new_disk.boot = False
    new_disk.type_ = "PERSISTENT"

    instance.disks.append(new_disk)

    instance_insert_request = compute_v1.InsertInstanceRequest()
    instance_insert_request.project = project_id
    instance_insert_request.zone = zone
    instance_insert_request.instance_resource = instance
    instance_insert_request.source_instance_template = instance_template.self_link

    operation = instance_client.insert(instance_insert_request)
    wait_for_extended_operation(operation, "instance creation")

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

REST

Verwenden Sie in der API den Abfrageparameter sourceInstanceTemplate und geben Sie im Anfragetext einer normalen Anfrage zum Erstellen einer Instanz alle Felder an, die Sie überschreiben möchten.

Das Überschreibungsverhalten in der API folgt den Regeln des Formats "JSON Merge Patch", das in RFC 7396 beschrieben wird.

Zum Beispiel:

  • Wenn Sie ein grundlegendes Feld überschreiben, wird das entsprechende grundlegende Feld in der Instanzvorlage durch den grundlegenden Feldwert in der Anfrage ersetzt. Grundlegende Felder umfassen machineType, sourceImage, name und so weiter.
  • Wenn Sie ein wiederkehrendes Feld überschreiben, werden alle wiederkehrenden Werte für dieses Attribut durch die entsprechenden Werte aus der Anfrage ersetzt. Wiederkehrende Felder sind in der Regel Attribute vom Typ list. Zum Beispiel sind disks und networkInterfaces wiederkehrende Felder.
  • Wenn Sie ein nested object überschreiben, wird das Objekt in der Instanzvorlage mit der entsprechenden Objektspezifikation der Anfrage zusammengeführt. Wenn sich in einem wiederkehrenden Feld ein verschachteltes Objekt befindet, wird das Feld gemäß den Regeln für wiederkehrende Felder behandelt. Labels sind eine Ausnahme von dieser Regel und werden auch dann als wiederkehrende Felder behandelt, wenn sie vom Typ object sind.

Beispiel: Sie haben eine Instanzvorlage mit zwei Nicht-Bootlaufwerken, aber Sie möchten eines der beiden Laufwerke außer Kraft setzen. Sie müssen die vollständige disks-Spezifikation in Ihrer Anfrage angeben, einschließlich aller beizubehaltenden Laufwerke.

Die URL für diese Anfrage:

POST https://compute.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/instances?
sourceInstanceTemplate=https://compute.googleapis.com/compute/v1/projects/myproject/global/instanceTemplates/example-instance-template

Der Anfragetext:

    {
      "disks": [
        {
          # Since you are overriding the repeated disk property, you must
          # specify a boot disk in the request, even if it is already
          # specified in the instance template
          "autoDelete": true,
          "boot": true,
          "initializeParams": {
            "sourceImage": "projects/debian-cloud/global/images/family/debian-8"
          },
          "mode": "READ_WRITE",
          "type": "PERSISTENT"
        },
        {
          # New disk you want to use
          "autoDelete": false,
          "boot": false,
          "mode": "READ_WRITE",
          "source": "zones/us-central1-f/disks/my-override-disk",
          "type": "PERSISTENT"
        },
        {
           # Assume this disk is already specified in instance template, but
           # you must specify it again since you are overriding the disks
           # property
          "autoDelete": false,
          "boot": false,
          "mode": "READ_WRITE",

          "source": "zones/us-central1-f/disks/my-other-disk-to-keep",
          "type": "PERSISTENT"
        }
      ],
      "machineType": "zones/us-central1-f/machineTypes/e2-standard-2",
      "name": "example-instance"
    }
    

Weitere Informationen