יצירת תבניות של מופעים

בדף הזה מוסבר איך ליצור ולנהל תבניות של הגדרות מכונה. תבניות של הגדרות מכונה מאפשרות לכם לציין את סוג המכונה, קובץ האימג' של דיסק האתחול, הרשת ומאפיינים אחרים של ה-VM שבהם אתם רוצים להשתמש כשאתם יוצרים מכונות וירטואליות (VM).

אתם יכולים להשתמש בתבניות של הגדרות מכונה כדי:

לפני שמתחילים

מגבלות

  • אפשר להשתמש ב-VPC משותף בממשקים שהם לא nic0 לתבניות של הגדרות מכונה ב-CLI של gcloud וב-REST, אבל לא במסוףGoogle Cloud .
  • אי אפשר לעדכן תבנית קיימת של הגדרות מכונה או לשנות אותה אחרי שהיא נוצרה. אם תבנית של הגדרות מכונה כבר לא עדכנית או שצריך לשנות את ההגדרות, יוצרים תבנית חדשה.
  • אם רוצים לציין משפחת תמונות בתבנית של הגדרות מכונה, אי אפשר להשתמש במסוף Google Cloud . במקום זאת, אפשר להשתמש ב-Google Cloud CLI או ב-REST.
  • אם רוצים לציין דיסקים אזוריים במקום דיסקים מקומיים בתבנית של הגדרות מכונה, אי אפשר להשתמש במסוף Google Cloud . במקום זאת, אפשר להשתמש ב-Google Cloud CLI או ב-REST.
  • אתם יכולים להשתמש בתבנית של הגדרות מכונה כדי ליצור מכונות וירטואליות עם דיסק אתחול מסוג Hyperdisk Balanced שנמצא במאגר אחסון, אם מאגר האחסון נמצא באותו אזור שבו נוצרה המכונה הווירטואלית. אי אפשר להשתמש בתבניות גלובליות של הגדרות מכונה כדי ליצור מכונות וירטואליות עם דיסקים שהם לא דיסקי אתחול שנמצאים ב-Storage Pool.

יצירת תבנית של הגדרות מכונה

את רוב המאפיינים של מכונות וירטואליות שאפשר לציין בבקשה ליצירת מכונה וירטואלית נפרדת, אפשר לציין גם בתבנית של הגדרות מכונה, כולל מטא-נתונים של מכונות וירטואליות, סקריפטים לטעינה בזמן ההפעלה, דיסקים קבועים וחשבונות שירות. צריך לציין את סוג המכונה, דיסק האתחול והרשת.

יוצרים תבנית של הגדרות מכונה אזורית או גלובלית באמצעותGoogle Cloud console, Google Cloud CLI או API. כדי ליצור תבנית גלובלית של הגדרות מכונה, אפשר גם להשתמש ב-Terraform או בספריות הלקוח של Cloud.

המסוף

  1. במסוף Google Cloud , נכנסים לדף תבניות של הגדרות מכונה.

    כניסה לדף Instance templates

    שאר השלבים מופיעים במסוף Google Cloud .

  2. לוחצים על יצירת תבנית של הגדרות מכונה.
  3. בוחרים את המיקום (Location) באופן הבא:
    1. אם רוצים להשתמש בתבנית של הגדרות המכונה בכמה אזורים, בוחרים באפשרות Global.
    2. אם רוצים לצמצם את התלות בין אזורים, בוחרים באפשרות Regional.
  4. אם בחרתם באפשרות האזורית, בוחרים את האזור (Region) שבו רוצים ליצור את התבנית של הגדרות המכונה.
  5. בשדות הבאים, אפשר להשתמש בערכי ברירת המחדל או לשנות אותם לפי הצורך. ערכי ברירת המחדל משתנים בהתאם למשפחת המכונות שבוחרים.

    • בוחרים סוג מכונה.
    • כדי לעדכן את הסוג או התמונה של דיסק האתחול, בקטע Boot disk לוחצים על Change.
    • כדי לעדכן את ההגדרות של ממשק הרשת או של כתובת ה-IP, לוחצים על Advanced options, ואז על Networking ועל ממשק הרשת שרוצים לערוך.
  6. אופציונלי: אם בחרתם קובץ אימג' שתומך במכונה וירטואלית מוגנת, אתם יכולים לשנות את הגדרות ה-מכונה וירטואלית מוגנת של ה-VM:

    1. לוחצים על Advanced options ואז על הכרטיסייה Security.
    2. כדי להשבית את האתחול המאובטח, מבטלים את הסימון בתיבה Turn on Secure Boot. אתחול מאובטח עוזר להגן על המכונות הווירטואליות מפני תוכנות זדוניות ורוטקיטים ברמת האתחול וברמת הליבה. למידע נוסף, ראו אתחול מאובטח.
    3. אם רוצים להשבית את מודול הפלטפורמה המהימנה הווירטואלי (vTPM), מבטלים את הסימון בתיבה Turn on vTPM. ה-vTPM מאפשר אתחול מדוד, שמאמת את תקינות המכונה הווירטואלית לפני האתחול ובמהלכו. מידע נוסף זמין במאמר מודול פלטפורמה מהימנה וירטואלי (vTPM).

    4. כדי להשבית את בדיקת התקינות, מבטלים את הסימון של התיבה Turn on Integrity Monitoring. בדיקת תקינות מאפשרת לכם לעקוב אחרי תקינות האתחול של המכונות הווירטואליות המוגנות באמצעות Cloud Monitoring. מידע נוסף זמין במאמר בדיקת תקינות.

  7. אופציונלי: בקטע Advanced options, לוחצים על הכרטיסיות כדי להתאים אישית את התבנית. לדוגמה, אפשר להוסיף עד 15 דיסקים משניים שהם לא דיסקים לאתחול.

  8. אופציונלי: לוחצים על Equivalent REST כדי לראות את גוף הבקשה ב-REST, שכולל את ייצוג ה-JSON של תבנית הגדרות המכונה.

  9. לוחצים על יצירה כדי ליצור את התבנית.

gcloud

כדי ליצור תבנית של הגדרות מכונה אזורית או גלובלית, משתמשים בפקודה instance-templates create. בתבנית של הגדרות מכונה אזורית, צריך להשתמש בדגל --instance-template-region כדי להגדיר את האזור של התבנית.

יוצרים תבנית של הגדרות מכונה אזורית באמצעות הפקודה הבאה.

gcloud compute instance-templates create INSTANCE_TEMPLATE_NAME \
    --instance-template-region=REGION

מחליפים את REGION באזור שבו רוצים ליצור את התבנית האזורית של הגדרות המכונה.

יוצרים תבנית גלובלית של הגדרות מכונה באמצעות הפקודה הבאה:

gcloud compute instance-templates create INSTANCE_TEMPLATE_NAME

אם לא מציינים הגדרות תבנית מפורשות, gcloud compute משתמש בערכי ברירת המחדל הבאים:

  • סוג המכונה: סוג המכונה, לדוגמה n1-standard-1
  • תמונה: התמונה האחרונה של Debian
  • דיסק אתחול: דיסק אתחול רגיל חדש שנקרא על שם ה-VM
  • רשת: רשת ה-VPC שמוגדרת כברירת מחדל
  • כתובת IP: כתובת IPv4 חיצונית זמנית
  • סוג המקבץ: IPV4_ONLY

אפשר גם לספק את הגדרות האישיות האלה באופן מפורש. לדוגמה:

gcloud compute instance-templates create my-instance-template \
    --machine-type=e2-standard-4 \
    --image-family=debian-13 \
    --image-project=debian-cloud \
    --boot-disk-size=250GB

אפשר להוסיף עד 15 דיסקים משניים שהם לא דיסקים לאתחול. מציינים את הדגל --create-disk לכל דיסק משני שיוצרים. כדי ליצור דיסקים משניים מתמונה ציבורית או מתמונה בהתאמה אישית, צריך לציין את המאפיינים image ו-image-project לכל דיסק בדגל --create-disk. כדי ליצור דיסק ריק, אל תכללו את המאפיינים האלה. אפשר גם לכלול מאפיינים לדיסק size ו-type. כדי לציין דיסקים אזוריים, משתמשים במאפיין replica-zones.

gcloud compute instance-templates create INSTANCE_TEMPLATE_NAME \
    --machine-type=MACHINE_TYPE \
    --create-disk=image-family=DISK_IMAGE_FAMILY,image-project=DISK_IMAGE_PROJECT,size=SIZE_GB_DISK1 \
    --create-disk=device-name=DISK_NAME,type=DISK_TYPE,size=SIZE_GB_DISK2,replica-zones=^:^ZONE:REMOTE_ZONE,boot=false

טיפ: כשמציינים את הפרמטר replica-zones של הדיסק, התווים ^:^ מציינים שתו ההפרדה בין הערכים הוא נקודתיים (:) במקום הפסיק הצפוי (,).

מחליפים את מה שכתוב בשדות הבאים:

  • ‫INSTANCE_TEMPLATE_NAME: שם התבנית
  • ‫MACHINE_TYPE: סוג המכונה של המכונות הווירטואליות
  • ‫DISK_IMAGE_FAMILY: משפחת תמונות לשימוש כדיסק שאינו דיסק אתחול

    למידע נוסף על משפחות של קובצי אימג', קראו את המאמר שיטות מומלצות לשימוש במשפחות של קובצי אימג' ב-Compute Engine.

    במקום זאת, אתם יכולים להשתמש בדגל --image=IMAGE כדי לציין גרסה ספציפית של קובץ אימג'.

    בדיסקים ריקים, אל תציינו את המאפיין image-family או image.

  • ‫DISK_IMAGE_PROJECT: פרויקט התמונה שמכיל את התמונה

    בדיסקים ריקים, אל תציינו את המאפיין image-project. למידע נוסף על קובצי אימג' ציבוריים, ראו קובצי אימג' ציבוריים.

  • ‫SIZE_GB_DISK1 ו-SIZE_GB_DISK2: הגודל של כל דיסק משני

  • ‫DISK_NAME: אופציונלי: שם הדיסק שמוצג למערכת ההפעלה של האורח אחרי שיוצרים את ה-VM.

  • ‫DISK_TYPE: אופציונלי: סוג הדיסק שרוצים ליצור. אם לא מציינים סוג דיסק, סוג הדיסק שמוגדר כברירת מחדל תלוי בערך של הדגל --machine-type.

  • ‫ZONE ו-REMOTE_ZONE: האזור שבו רוצים ליצור את הדיסק האזורי והאזור שאליו רוצים לשכפל אותו.

    בדיסקי אחסון מקומי, אל תכללו את המאפיין replica-zones.

אם בחרתם תמונה שתומכת במכונה וירטואלית מוגנת, אתם יכולים לשנות את הגדרות המכונה הווירטואלית המוגנת של המכונה באמצעות אחד מהדגלים הבאים:

  • ‫--no-shielded-secure-boot: משבית את האתחול המאובטח

    אתחול מאובטח עוזר להגן על המכונות הווירטואליות מפני תוכנות זדוניות ורוטקיטים ברמת האתחול וברמת הליבה. מידע נוסף זמין במאמר אתחול מאובטח.

  • ‫--no-shielded-vtpm: משבית את מודול הפלטפורמה המהימנה הווירטואלית (vTPM)

    ה-vTPM מאפשר אתחול מדוד, שמאמת את תקינות ה-VM לפני האתחול ובמהלכו. מידע נוסף זמין במאמר מודול פלטפורמה מהימנה וירטואלי (vTPM).

  • ‫--no-shielded-integrity-monitoring: משבית את בדיקת התקינות

    בדיקת התקינות מאפשרת לכם לעקוב אחרי תקינות האתחול של המכונות הווירטואליות המוגנות באמצעות Cloud Monitoring. מידע נוסף זמין במאמר בדיקת תקינות.

רשימה של כל פקודות המשנה והדגלים האפשריים מופיעה במאמרי העזרה בנושא instance-templates.

Terraform

כדי ליצור תבנית של הגדרות מכונה, אפשר להשתמש באחד מהמשאבים הבאים:

בדוגמה הבאה נוצרת תבנית גלובלית של הגדרות מכונה:

resource "google_compute_instance_template" "foobar" {
  name         = "my-instance-template"
  machine_type = "e2-standard-4"

  disk {
    source_image = "debian-cloud/debian-13"
    disk_size_gb = 250
  }

  network_interface {
    network = "default"

    # default access config, defining external IP configuration
    access_config {
      network_tier = "PREMIUM"
    }
  }

  # To avoid embedding secret keys or user credentials in the instances, Google recommends that you use custom service accounts with the following access scopes.
  service_account {
    scopes = [
      "https://www.googleapis.com/auth/cloud-platform"
    ]
  }
}

כדי ללמוד איך להחיל הגדרות ב-Terraform או להסיר אותן, ראו פקודות בסיסיות ב-Terraform.

המשך

import (
	"context"
	"fmt"
	"io"

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

// createTemplate creates a new instance template with the provided name and a specific instance configuration.
func createTemplate(w io.Writer, projectID, templateName string) error {
	// projectID := "your_project_id"
	// templateName := "your_template_name"

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

	req := &computepb.InsertInstanceTemplateRequest{
		Project: projectID,
		InstanceTemplateResource: &computepb.InstanceTemplate{
			Name: proto.String(templateName),
			Properties: &computepb.InstanceProperties{
				// The template describes the size and source image of the boot disk
				// to attach to the instance.
				Disks: []*computepb.AttachedDisk{
					{
						InitializeParams: &computepb.AttachedDiskInitializeParams{
							DiskSizeGb:  proto.Int64(250),
							SourceImage: proto.String("projects/debian-cloud/global/images/family/debian-12"),
						},
						AutoDelete: proto.Bool(true),
						Boot:       proto.Bool(true),
					},
				},
				MachineType: proto.String("e2-standard-4"),
				// The template connects the instance to the `default` network,
				// without specifying a subnetwork.
				NetworkInterfaces: []*computepb.NetworkInterface{
					{
						Name: proto.String("global/networks/default"),
						// The template lets the instance use an external IP address.
						AccessConfigs: []*computepb.AccessConfig{
							{
								Name:        proto.String("External NAT"),
								Type:        proto.String(computepb.AccessConfig_ONE_TO_ONE_NAT.String()),
								NetworkTier: proto.String(computepb.AccessConfig_PREMIUM.String()),
							},
						},
					},
				},
			},
		},
	}

	op, err := instanceTemplatesClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create instance template: %w", err)
	}

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

	fmt.Fprintf(w, "Instance template created\n")

	return nil
}

Java

import com.google.cloud.compute.v1.AccessConfig;
import com.google.cloud.compute.v1.AccessConfig.NetworkTier;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.GlobalOperationsClient;
import com.google.cloud.compute.v1.InsertInstanceTemplateRequest;
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.NetworkInterface;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateInstanceTemplate {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // projectId: project ID or project number of the Cloud project you use.
    // templateName: name of the new template to create.
    String projectId = "your-project-id";
    String templateName = "template-name";
    createInstanceTemplate(projectId, templateName);
  }

  /*
    Create a new instance template with the provided name and a specific
    instance configuration.
   */
  public static void createInstanceTemplate(String projectId, String templateName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    try (InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create()) {

      String machineType = "e2-standard-4";
      String sourceImage = "projects/debian-cloud/global/images/family/debian-13";

      // The template describes the size and source image of the boot disk
      // to attach to the instance.
      AttachedDisk attachedDisk = AttachedDisk.newBuilder()
          .setInitializeParams(AttachedDiskInitializeParams.newBuilder()
              .setSourceImage(sourceImage)
              .setDiskType("pd-balanced")
              .setDiskSizeGb(250).build())
          .setAutoDelete(true)
          .setBoot(true).build();

      // The template connects the instance to the `default` network,
      // without specifying a subnetwork.
      NetworkInterface networkInterface = NetworkInterface.newBuilder()
          .setName("global/networks/default")
          // The template lets the instance use an external IP address.
          .addAccessConfigs(AccessConfig.newBuilder()
              .setName("External NAT")
              .setType(AccessConfig.Type.ONE_TO_ONE_NAT.toString())
              .setNetworkTier(NetworkTier.PREMIUM.toString()).build()).build();

      InstanceProperties instanceProperties = InstanceProperties.newBuilder()
          .addDisks(attachedDisk)
          .setMachineType(machineType)
          .addNetworkInterfaces(networkInterface).build();

      InsertInstanceTemplateRequest insertInstanceTemplateRequest = InsertInstanceTemplateRequest
          .newBuilder()
          .setProject(projectId)
          .setInstanceTemplateResource(InstanceTemplate.newBuilder()
              .setName(templateName)
              .setProperties(instanceProperties).build()).build();

      // Create the Instance Template.
      Operation response = instanceTemplatesClient.insertAsync(insertInstanceTemplateRequest)
          .get(3, TimeUnit.MINUTES);

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

  public static void createInstanceTemplateWithDiskType(String projectId, String templateName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    try (InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create();
        GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.create()) {

      AttachedDisk disk = AttachedDisk.newBuilder()
          .setInitializeParams(AttachedDiskInitializeParams.newBuilder()
              .setDiskSizeGb(10)
              .setDiskType("pd-balanced")
              .setSourceImage("projects/debian-cloud/global/images/family/debian-13").build())
          .setAutoDelete(true)
          .setBoot(true)
          .setType(AttachedDisk.Type.PERSISTENT.toString()).build();

      InstanceTemplate instanceTemplate = InstanceTemplate.newBuilder()
          .setName(templateName)
          .setProperties(InstanceProperties.newBuilder()
              .setMachineType("n1-standard-1")
              .addDisks(disk)
              .addNetworkInterfaces(NetworkInterface.newBuilder()
                  .setName("global/networks/default").build()).build()).build();

      InsertInstanceTemplateRequest insertInstanceTemplateRequest = InsertInstanceTemplateRequest
          .newBuilder()
          .setProject(projectId)
          .setInstanceTemplateResource(instanceTemplate).build();

      Operation response = instanceTemplatesClient.insertAsync(insertInstanceTemplateRequest)
          .get(3, TimeUnit.MINUTES);

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

Node.js

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const templateName = 'your_template_name';

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

// Create a new instance template with the provided name and a specific instance configuration.
async function createTemplate() {
  const instanceTemplatesClient = new compute.InstanceTemplatesClient();

  const [response] = await instanceTemplatesClient.insert({
    project: projectId,
    instanceTemplateResource: {
      name: templateName,
      properties: {
        disks: [
          {
            // The template describes the size and source image of the boot disk
            // to attach to the instance.
            initializeParams: {
              diskSizeGb: '250',
              sourceImage:
                'projects/debian-cloud/global/images/family/debian-13',
            },
            autoDelete: true,
            boot: true,
          },
        ],
        machineType: 'e2-standard-4',
        // The template connects the instance to the `default` network,
        // without specifying a subnetwork.
        networkInterfaces: [
          {
            // Use the network interface provided in the networkName argument.
            name: 'global/networks/default',
            // The template lets the instance use an external IP address.
            accessConfigs: [
              {
                name: 'External NAT',
                type: 'ONE_TO_ONE_NAT',
                networkTier: 'PREMIUM',
              },
            ],
          },
        ],
      },
    },
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.GlobalOperationsClient();

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

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

createTemplate();

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_template(project_id: str, template_name: str) -> compute_v1.InstanceTemplate:
    """
    Create a new instance template with the provided name and a specific
    instance configuration.

    Args:
        project_id: project ID or project number of the Cloud project you use.
        template_name: name of the new template to create.

    Returns:
        InstanceTemplate object that represents the new instance template.
    """
    # The template describes the size and source image of the boot disk
    # to attach to the instance.
    disk = compute_v1.AttachedDisk()
    initialize_params = compute_v1.AttachedDiskInitializeParams()
    initialize_params.source_image = (
        "projects/debian-cloud/global/images/family/debian-13"
    )
    initialize_params.disk_size_gb = 250
    disk.initialize_params = initialize_params
    disk.auto_delete = True
    disk.boot = True

    # The template connects the instance to the `default` network,
    # without specifying a subnetwork.
    network_interface = compute_v1.NetworkInterface()
    network_interface.name = "global/networks/default"

    # The template lets the instance use an external IP address.
    access_config = compute_v1.AccessConfig()
    access_config.name = "External NAT"
    access_config.type_ = "ONE_TO_ONE_NAT"
    access_config.network_tier = "PREMIUM"
    network_interface.access_configs = [access_config]

    template = compute_v1.InstanceTemplate()
    template.name = template_name
    template.properties.disks = [disk]
    template.properties.machine_type = "e2-standard-4"
    template.properties.network_interfaces = [network_interface]

    template_client = compute_v1.InstanceTemplatesClient()
    operation = template_client.insert(
        project=project_id, instance_template_resource=template
    )

    wait_for_extended_operation(operation, "instance template creation")

    return template_client.get(project=project_id, instance_template=template_name)

REST

כדי ליצור תבנית של הגדרות מכונה אזורית, שולחים בקשת POST אל ה-method‏ regionInstanceTemplates.insert, באופן הבא:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/instanceTemplates

כדי ליצור תבנית גלובלית של הגדרות מכונה, שולחים בקשת POST ל-method‏ instanceTemplates.insert:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/instanceTemplates

אפשר להוסיף עד 15 דיסקים משניים שאינם דיסקי אתחול באמצעות המאפיין disks, עם שדה לכל דיסק נוסף. לכל דיסק נוסף, אפשר לבצע את הפעולות הבאות:

  • ליצור דיסקים נוספים עם קובץ אימג' ציבורי או בהתאמה אישית.
  • כדי להוסיף דיסק ריק, מגדירים את הרשומה initializeParams בלי ערך sourceImage.
  • כדי ליצור דיסקים אזוריים, מגדירים את הרשומה initializeParams עם המאפיין replicaZones.

בגוף הבקשה, מציינים את מאפייני התבנית:

{
  "name": "INSTANCE_TEMPLATE_NAME",
  "properties": {
    "machineType": "MACHINE_TYPE",
    "networkInterfaces": [
      {
        "network": "global/networks/default",
        "accessConfigs":
        [
          {
            "name": "external-IP",
            "type": "ONE_TO_ONE_NAT"
          }
        ]
      }
    ],
    "disks":
    [
      {
        "type": "PERSISTENT",
        "boot": true,
        "mode": "READ_WRITE",
        "initializeParams":
        {
          "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"
        }
      },
      {
        "type": "PERSISTENT",
        "boot": false,
        "deviceName": "DISK_NAME",
        "initializeParams":
        {
          "replicaZones": [
              "projects/PROJECT_NAME/zones/ZONE",
              "projects/PROJECT_NAME/zones/REMOTE_ZONE"
          ]
        }
      }
    ]
  }
}

מחליפים את מה שכתוב בשדות הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט
  • ‫REGION: האזור שבו רוצים ליצור את התבנית האזורית של הגדרות המכונה
  • ‫INSTANCE_TEMPLATE_NAME: השם של התבנית של הגדרות המכונה
  • ‫ZONE: האזור שבו נמצאות המכונות הווירטואליות
  • ‫MACHINE_TYPE: סוג המכונה של המכונות הווירטואליות

  • ‫IMAGE_PROJECT: פרויקט התמונה שמכיל את התמונה

    למידע נוסף על קובצי אימג' ציבוריים, ראו קובצי אימג' ציבוריים.

  • ‫IMAGE או IMAGE_FAMILY: מציינים אחת מהאפשרויות הבאות:
    • ‫IMAGE: גרסה ספציפית של קובץ האימג'

      לדוגמה, "sourceImage": "projects/debian-cloud/global/images/debian-10-buster-v20200309"

    • ‫IMAGE_FAMILY: משפחת תמונות

      כך נוצרת ה-VM מקובץ אימג' של מערכת ההפעלה העדכני ביותר, שלא הוצא משימוש. לדוגמה, אם מציינים את "sourceImage": "projects/debian-cloud/global/images/family/debian-10", המערכת של Compute Engine יוצרת מכונה וירטואלית מהגרסה האחרונה של קובץ האימג' של מערכת ההפעלה במשפחת קובצי האימג' של Debian 10.

      למידע נוסף על משפחות של קובצי אימג', קראו את המאמר שיטות מומלצות לשימוש במשפחות של קובצי אימג' ב-Compute Engine.

  • ‫DISK_NAME: אופציונלי: שם הדיסק שמוצג למערכת ההפעלה של האורח אחרי שיוצרים את ה-VM.

  • ‫PROJECT_NAME: הפרויקט שמשויך למכונה הווירטואלית

  • ‫REMOTE_ZONE: האזור שאליו צריך לשכפל את הדיסק האזורי

אפשר לציין אחת מהאפשרויות הבאות למאפיין disks:

  • מציינים את הערך initializeParams כדי ליצור דיסקי אתחול לכל מכונה. אפשר ליצור דיסקים באמצעות קובצי אימג' ציבוריים או בהתאמה אישית (או משפחות של קובצי אימג') באמצעות המאפיין sourceImage, כמו שמוצג בדוגמה הקודמת. כדי להוסיף דיסקים ריקים, אל תציינו sourceImage. אפשר גם להוסיף עד 15 דיסקים משניים שאינם דיסקים לאתחול, באמצעות המאפיין initializeParams לכל דיסק נוסף.

  • מציינים את הערך source כדי לצרף דיסק אתחול קיים. אם מצרפים דיסק אתחול קיים, אפשר ליצור רק מכונה אחת מהתבנית.

אפשר גם לציין את המאפיינים diskSizeGb,‏ diskType ו-labels בשביל initializeParams, ואת המאפיין diskSizeGb בשביל source.

אם בחרתם תמונה שתומכת במכונה וירטואלית מוגנת, אתם יכולים לשנות את ההגדרות של המכונה הווירטואלית המוגנת באמצעות הפריטים הבוליאניים הבאים בגוף הבקשה:

  • ‫enableSecureBoot: הפעלה או השבתה של אתחול מאובטח

    אתחול מאובטח עוזר להגן על המכונות הווירטואליות מפני תוכנות זדוניות ורוטקיטים ברמת האתחול וברמת הליבה. מידע נוסף זמין במאמר אתחול מאובטח.

  • ‫enableVtpm: הפעלה או השבתה של מודול הפלטפורמה המהימנה הווירטואלית (vTPM)

    ה-vTPM מאפשר אתחול מדוד, שמאמת את תקינות ה-VM לפני האתחול ובמהלכו. מידע נוסף זמין במאמר מודול פלטפורמה מהימנה וירטואלי (vTPM).

  • ‫enableIntegrityMonitoring: הפעלה או השבתה של בדיקת התקינות

    בדיקת התקינות מאפשרת לכם לעקוב אחרי תקינות ההפעלה בזמן הריצה של המכונות הווירטואליות המוגנות, ולאמת אותה באמצעות דוחות של Cloud Monitoring. מידע נוסף זמין במאמר בדיקת תקינות.

מידע נוסף על פרמטרים של בקשות זמין בשיטה instanceTemplates.insert.

יצירת תבנית של הגדרות מכונה על סמך מכונה קיימת

אתם יכולים להשתמש ב-REST או ב-CLI של gcloud כדי לשמור את ההגדרות של מכונה וירטואלית קיימת כתבנית של הגדרות מכונה. אפשר לשנות את האופן שבו דיסקי המקור מוגדרים בתבנית.

אם אתם צריכים לשנות מאפיינים אחרים, קודם צרו תבנית של הגדרות מכונה שמבוססת על מכונה קיימת, ואז צרו תבנית דומה עם שינויים נוספים.

gcloud

משתמשים בפקודה gcloud compute instance-templates create עם הדגלים --source-instance ו---source-instance-zone. אם רוצים ליצור תבנית של הגדרות מכונה אזורית, צריך להשתמש גם בדגל --instance-template-region כדי לציין את האזור של התבנית.

כדי ליצור תבנית של הגדרות מכונה אזורית, משתמשים בפקודה הבאה:

 gcloud compute instance-templates create INSTANCE_TEMPLATE_NAME \
     --source-instance=SOURCE_INSTANCE \
     --source-instance-zone=SOURCE_INSTANCE_ZONE \
     --instance-template-region=REGION

כדי ליצור תבנית גלובלית של הגדרות מכונה, משתמשים בפקודה הבאה:

gcloud compute instance-templates create INSTANCE_TEMPLATE_NAME \
    --source-instance=SOURCE_INSTANCE \
    --source-instance-zone=SOURCE_INSTANCE_ZONE

כדי לשנות את האופן שבו מוגדרים הדיסקים של מכונת המקור, מוסיפים דגל --configure-disk אחד או יותר.

בדוגמה הבאה נוצרת תבנית גלובלית של הגדרות מכונה ממכונה קיימת, והדיסק של מכונת המקור מוחלף במפרט שאתם מספקים.

  gcloud compute instance-templates create INSTANCE_TEMPLATE_NAME \
      --source-instance=SOURCE_INSTANCE \
      --source-instance-zone=SOURCE_INSTANCE_ZONE \
      --configure-disk= \
      device-name=SOURCE_DISK, \
      instantiate-from=INSTANTIATE_OPTIONS, \
      auto-delete=AUTO_DELETE

מחליפים את מה שכתוב בשדות הבאים:

  • ‫INSTANCE_TEMPLATE_NAME הוא שם התבנית שרוצים ליצור.
  • ‫SOURCE_INSTANCE הוא שם המכונה שמשמשת כמודל לתבנית החדשה.
  • ‫SOURCE_INSTANCE_ZONE הוא האזור שבו נמצא המכונה של המקור.
  • ‫SOURCE_DISK הוא השם של דיסק במכונה המקורית שרוצים לשנות בתבנית.
  • ‫INSTANTIATE_OPTIONS מציין אם לכלול את הדיסק ובאיזו תמונה להשתמש. הערכים התקינים תלויים בסוג הדיסק:

    • ‫source-image או source-image-family (תקף רק לדיסקים של הפעלה ודיסקים קבועים אחרים לקריאה וכתיבה). ציינו את האפשרות הזו אם אתם רוצים להשתמש באותה תמונת מקור או באותה משפחת תמונות מקור ששימשה ליצירת הדיסק במכונה הווירטואלית של המקור.
    • ‫custom-image (תקף רק לדיסקים לאתחול ולדיסקים מתמידים אחרים לקריאה ולכתיבה). אם אתם רוצים לשמור את האפליקציות וההגדרות מהמכונות הווירטואליות המקוריות בתבנית של הגדרות המכונה, אתם יכולים ליצור קובץ אימג' בהתאמה אישית ולציין אותו כשאתם יוצרים את התבנית. אם ציינתם תמונה מותאמת אישית, צריך לציין את הנתיב או את כתובת ה-URL שלה, כמו בדוגמה הבאה. לחלופין, אפשר לציין משפחת תמונות בפורמט הבא:

      --configure-disk=device-name=DATA_DISK_NAME,instantiate-from=custom-image, \
      custom-image=projects/PROJECT_ID/global/images/family/IMAGE_FAMILY_NAME
      
    • ‫attach-read-only (תקף רק לדיסקים לקריאה בלבד).

    • ‫blank (תקף רק לדיסקים לאחסון מתמיד שלא משמשים לאתחול ולכונני SSD מקומיים). אם מציינים את המאפיין הזה, כשמשתמשים בתבנית כדי ליצור מכונה חדשה, הדיסק נוצר ללא פורמט. כדי להשתמש בדיסק בהגדרה שניתנת להתאמה, צריך לפרמט ולטעון אותו בסקריפט לטעינה בזמן ההפעלה.

    • do-not-include (תקף רק לדיסקי אחסון מתמידים שאינם דיסקי אתחול ולדיסקים לקריאה בלבד).

  • הדגל AUTO_DELETE מציין אם הדיסק נמחק באופן אוטומטי כשהמכונה נמחקת. הערכים התקינים הם: false,‏ no,‏ true ו-yes.

לדוגמה, הפקודה הבאה יוצרת תבנית של הגדרות מכונה שמבוססת על my-source-instance, עם אפשרות להשתמש בתמונה המקורית מ-data-disk-a, אבל מגדירה מחיקה אוטומטית ל-true ומחליפה את data-disk-b בתמונה בהתאמה אישית.

 gcloud compute instance-templates create my-instance-template  \
     --source-instance=my-source-instance \
     --configure-disk=device-name=data-disk-a,instantiate-from=source-image,auto-delete=true \
     --configure-disk=device-name=data-disk-b,instantiate-from=custom-image,custom-image=projects/cps-cloud/global/images/cos-89-16108-403-15

המשך

import (
	"context"
	"fmt"
	"io"

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

// createTemplateFromInstance creates a new instance template based on an existing instance.
// This new template specifies a different boot disk.
func createTemplateFromInstance(w io.Writer, projectID, instance, templateName string) error {
	// projectID := "your_project_id"
	// instance := "projects/project/zones/zone/instances/instance"
	// templateName := "your_template_name"

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

	req := &computepb.InsertInstanceTemplateRequest{
		Project: projectID,
		InstanceTemplateResource: &computepb.InstanceTemplate{
			Name:           proto.String(templateName),
			SourceInstance: proto.String(instance),
			SourceInstanceParams: &computepb.SourceInstanceParams{
				DiskConfigs: []*computepb.DiskInstantiationConfig{
					{
						// Device name must match the name of a disk attached to the instance
						// your template is based on.
						DeviceName: proto.String("disk-1"),
						// Replace the original boot disk image used in your instance with a Rocky Linux image.
						InstantiateFrom: proto.String(computepb.DiskInstantiationConfig_CUSTOM_IMAGE.String()),
						CustomImage:     proto.String("projects/rocky-linux-cloud/global/images/family/rocky-linux-8"),
						// Override the auto_delete setting.
						AutoDelete: proto.Bool(true),
					},
				},
			},
		},
	}

	op, err := instanceTemplatesClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create instance template: %w", err)
	}

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

	fmt.Fprintf(w, "Instance template created\n")

	return nil
}

Java


import com.google.cloud.compute.v1.DiskInstantiationConfig;
import com.google.cloud.compute.v1.DiskInstantiationConfig.InstantiateFrom;
import com.google.cloud.compute.v1.GlobalOperationsClient;
import com.google.cloud.compute.v1.InsertInstanceTemplateRequest;
import com.google.cloud.compute.v1.InstanceTemplate;
import com.google.cloud.compute.v1.InstanceTemplatesClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.SourceInstanceParams;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateTemplateFromInstance {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // projectId: project ID or project number of the Cloud project you use.
    // instance: the instance to base the new template on. This value uses the following format:
    // **NOTE**: "projects/{project}/zones/{zone}/instances/{instance_name}"
    // templateName: name of the new template to create.
    String projectId = "your-project-id";
    String templateName = "template-name";
    String instance = String.format("projects/%s/zones/%s/instances/%s", projectId, "zone",
        "instanceName");
    createTemplateFromInstance(projectId, templateName, instance);
  }

  // Create a new instance template based on an existing instance.
  // This new template specifies a different boot disk.
  public static void createTemplateFromInstance(String projectId, String templateName,
      String instance)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    try (InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create();
        GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.create()) {

      SourceInstanceParams sourceInstanceParams = SourceInstanceParams.newBuilder()
          .addDiskConfigs(DiskInstantiationConfig.newBuilder()
              // Device name must match the name of a disk attached to the instance you are
              // basing your template on.
              .setDeviceName("disk-1")
              // Replace the original boot disk image used in your instance
              // with a Rocky Linux image.
              .setInstantiateFrom(InstantiateFrom.CUSTOM_IMAGE.toString())
              .setCustomImage(
                  String.format("projects/%s/global/images/family/%s", "rocky-linux-cloud",
                      "rocky-linux-8"))
              // Override the AutoDelete setting.
              .setAutoDelete(true).build())
          .build();

      InstanceTemplate instanceTemplate = InstanceTemplate.newBuilder()
          .setName(templateName)
          .setSourceInstance(instance)
          .setSourceInstanceParams(sourceInstanceParams)
          .build();

      InsertInstanceTemplateRequest insertInstanceTemplateRequest = InsertInstanceTemplateRequest
          .newBuilder()
          .setProject(projectId)
          .setInstanceTemplateResource(instanceTemplate)
          .build();

      Operation operation = instanceTemplatesClient.insertCallable()
          .futureCall(insertInstanceTemplateRequest).get(3, TimeUnit.MINUTES);

      Operation response = globalOperationsClient.wait(projectId, operation.getName());

      if (response.hasError()) {
        System.out.println("Instance Template creation failed ! ! " + response);
        return;
      }
      System.out.printf("Instance Template creation operation status %s: %s", templateName,
          response.getStatus());
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const instance = 'projects/project/zones/zone/instances/instance';
// const templateName = 'your_template_name';

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

// Create a new instance template based on an existing instance.
// This new template specifies a different boot disk.
async function createTemplateFromInstance() {
  const instanceTemplatesClient = new compute.InstanceTemplatesClient();

  const [response] = await instanceTemplatesClient.insert({
    project: projectId,
    instanceTemplateResource: {
      name: templateName,
      sourceInstance: instance,
      sourceInstanceParams: {
        diskConfigs: [
          {
            // Device name must match the name of a disk attached to the instance
            // your template is based on.
            deviceName: 'disk-1',
            // Replace the original boot disk image used in your instance with a Rocky Linux image.
            instantiateFrom: 'CUSTOM_IMAGE',
            customImage:
              'projects/rocky-linux-cloud/global/images/family/rocky-linux-8',
            // Override the auto_delete setting.
            autoDelete: true,
          },
        ],
      },
    },
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.GlobalOperationsClient();

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

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

createTemplateFromInstance();

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_template_from_instance(
    project_id: str, instance: str, template_name: str
) -> compute_v1.InstanceTemplate:
    """
    Create a new instance template based on an existing instance.
    This new template specifies a different boot disk.

    Args:
        project_id: project ID or project number of the Cloud project you use.
        instance: the instance to base the new template on. This value uses
            the following format: "projects/{project}/zones/{zone}/instances/{instance_name}"
        template_name: name of the new template to create.

    Returns:
        InstanceTemplate object that represents the new instance template.
    """
    disk = compute_v1.DiskInstantiationConfig()
    # Device name must match the name of a disk attached to the instance you are
    # basing your template on.
    disk.device_name = "disk-1"
    # Replace the original boot disk image used in your instance with a Rocky Linux image.
    disk.instantiate_from = "CUSTOM_IMAGE"
    disk.custom_image = "projects/rocky-linux-cloud/global/images/family/rocky-linux-8"
    # Override the auto_delete setting.
    disk.auto_delete = True

    template = compute_v1.InstanceTemplate()
    template.name = template_name
    template.source_instance = instance
    template.source_instance_params = compute_v1.SourceInstanceParams()
    template.source_instance_params.disk_configs = [disk]

    template_client = compute_v1.InstanceTemplatesClient()
    operation = template_client.insert(
        project=project_id, instance_template_resource=template
    )

    wait_for_extended_operation(operation, "instance template creation")

    return template_client.get(project=project_id, instance_template=template_name)

REST

כדי ליצור תבנית של הגדרות מכונה אזורית, משתמשים ב-method ‏regionInstanceTemplates.insert, וכדי ליצור תבנית של הגדרות מכונה גלובלית, משתמשים ב-method ‏instanceTemplates.insert.

בבקשה, צריך לציין את השדה sourceInstance. כדי לשנות את האופן שבו מוגדרים הדיסקים של מכונת המקור, מוסיפים שדה diskConfigs אחד או יותר.

לדוגמה, כדי ליצור תבנית גלובלית של הגדרות מכונה ממכונה קיימת, אפשר לבצע את הקריאה הבאה:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/instanceTemplates

{
  "name": "INSTANCE_TEMPLATE_NAME",
  "sourceInstance": "zones/SOURCE_INSTANCE_ZONE/instances/SOURCE_INSTANCE",
  "sourceInstanceParams": {
    "diskConfigs": [
      {
        "deviceName": "SOURCE_DISK",
        "instantiateFrom": "INSTANTIATE_OPTIONS",
        "autoDelete": false
      }
    ]
  }
}

מחליפים את מה שכתוב בשדות הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט
  • ‫INSTANCE_TEMPLATE_NAME: השם של התבנית החדשה
  • ‫SOURCE_INSTANCE_ZONE: האזור של מכונת המקור
  • ‫SOURCE_INSTANCE: השם של מכונת המקור שמשמשת כמודל לתבנית של הגדרות המכונה הזו
  • ‫SOURCE_DISK: השם של דיסק במכונה המקורית שרוצים לשנות בתבנית
  • ‫INSTANTIATE_OPTIONS: מציין אם לכלול את הדיסק ובאיזו קובץ אימג' להשתמש

    הערכים התקינים תלויים בסוג הדיסק:

    • ‫source-image או source-image-family (תקף רק לדיסקים של אתחול ולדיסקים אחרים של קריאה וכתיבה מתמידים).
    • ‫custom-image (תקף רק לדיסקים לאתחול ולדיסקים מתמידים אחרים לקריאה ולכתיבה). אם אתם רוצים לשמור את האפליקציות וההגדרות מהמכונות הווירטואליות המקוריות בתבנית של הגדרות המכונה, אתם יכולים ליצור קובץ אימג' בהתאמה אישית ולציין אותו כשאתם יוצרים את התבנית. אם ציינתם תמונה מותאמת אישית, צריך לציין את הנתיב או את כתובת ה-URL שלה, כמו בדוגמה הבאה. לחלופין, אפשר לציין משפחת תמונות בפורמט הבא:

        "diskConfigs": [
          {
            "deviceName": DATA_DISK_NAME,
            "instantiateFrom": custom-image,
            "customImage": "projects/PROJECT_ID/global/images/family/IMAGE_FAMILY_NAME"
          }
        ]
      
    • ‫attach-read-only (תקף רק לדיסקים לקריאה בלבד).

    • ‫blank (תקף רק לדיסקים לאחסון מתמיד שלא משמשים לאתחול ולכונני SSD מקומיים). אם מציינים את המאפיין הזה, כשמשתמשים בתבנית כדי ליצור מכונה חדשה, הדיסק נוצר ללא פורמט. כדי להשתמש בדיסק בהגדרה שניתנת להתאמה, צריך לפרמט ולטעון אותו בסקריפט לטעינה בזמן ההפעלה.

    • do-not-include (תקף רק לדיסקי אחסון מתמידים שאינם דיסקי אתחול ולדיסקים לקריאה בלבד).

בדוגמה הבאה נוצרת תבנית חדשה של הגדרות מכונה שמבוססת על my-source-instance. בתבנית של הגדרות המכונה, התמונה של data-disk-a מוחלפת ב-projects/cos-cloud/global/images/cos-89-16108-403-15.

POST https://compute.googleapis.com/compute/v1/projects/my_project/global/instanceTemplates

{
  "name": "my-instance-template",
  "sourceInstance": "zones/us-central1-a/instances/my-source-instance",
  "sourceInstanceParams":
  {
    "diskConfigs":
    [
      {
        "deviceName": "data-disk-a",
        "instantiateFrom": "custom-image",
        "customImage": "projects/cos-cloud/global/images/cos-89-16108-403-15"
      }
    ]
  }
}

בטבלה הבאה מפורטות האפשרויות להחלפת דיסקים בתבנית.

סוג הדיסק אפשרויות
דיסק אתחול
  • [ברירת מחדל] שימוש באותה תמונת מקור או באותה משפחת תמונות ששימשה ליצירת דיסק האתחול במכונה המקורית.
  • אפשר להשתמש בכתובת ה-URL של כל תמונה (מותאמת אישית או ציבורית) כמו שמתואר בדוגמה הקודמת, או לציין משפחת תמונות בפורמט הבא:
  • projects/exampleproject/global/images/family/IMAGE_FAMILY_NAME

דיסקים אחרים לאחסון מתמיד עם הרשאות קריאה/כתיבה
  • [ברירת מחדל] שימוש באותה תמונת מקור או באותה משפחת תמונות מקור ששימשה ליצירת הדיסק במכונה המקורית. הערה: אם לדיסק של מכונת המקור אין מאפיין של תמונת מקור או משפחת תמונות מקור, הוא נכלל בתבנית כדיסק ריק.
  • אפשר להשתמש בכתובת ה-URL של כל תמונה (מותאמת אישית או ציבורית) כמו שמתואר בדוגמה הקודמת, או לציין משפחת תמונות בפורמט הבא:

    projects/exampleproject/global/images/family/IMAGE_FAMILY_NAME

  • במקום זאת, צריך להשתמש בדיסק ריק בתבנית. כשמשתמשים בתבנית כדי ליצור מכונה חדשה, הדיסק הזה נוצר ללא פורמט. כדי להשתמש בדיסק בהגדרה שניתנת להתאמה, צריך לפרמט ולטעון אותו בסקריפט לטעינה בזמן ההפעלה.
  • אל תכללו את הדיסק.
דיסקים לקריאה בלבד
  • ‫[ברירת מחדל] הכללת הדיסק במצב קריאה בלבד.
  • אל תכללו את הדיסק.
כונני SSD מקומיים
  • [ברירת מחדל] הוספת SSD מקומי ריק. כשמשתמשים בתבנית כדי ליצור מכונה חדשה, הדיסק הזה נוצר ללא פורמט. כדי להשתמש בדיסק בהגדרה שניתנת להתאמה, צריך לפרמט ולטעון אותו בסקריפט לטעינה בזמן ההפעלה.

לכל דיסק אפשר גם לשנות את המאפיין auto-delete כדי לציין אם הדיסק יימחק כשהמכונה שמשויכת אליו תימחק.

כברירת מחדל, אם לא מציינים אפשרויות שינוי, הגדרת הדיסק בתבנית תואמת למכונה המקורית.

יצירת תבנית של הגדרות מכונה על סמך תבנית קיימת

אי אפשר לעדכן תבנית קיימת של הגדרות מכונה. אבל אם תבנית של הגדרות מכונה מתיישנת או אם צריך לבצע שינויים, אפשר ליצור תבנית אחרת עם מאפיינים דומים באמצעות המסוף.

  1. נכנסים לדף Instance templates.

    כניסה לדף Instance templates

  2. לוחצים על תבנית המכונה שרוצים להעתיק ולעדכן.

  3. לוחצים על יצירת תמונה דומה.

  4. מעדכנים את ההגדרות בתבנית החדשה.

  5. לוחצים על יצירה.

יצירת תבנית של הגדרות מכונה למכונות וירטואליות עם GPU

כשיוצרים תבנית של הגדרות מכונה, אפשר להגדיר אותה ליצירת מכונות וירטואליות עם מעבדי GPU מצורפים. לשם כך, צריך לציין את הפרטים הבאים:

המסוף

כדי ליצור תבנית של הגדרות מכונה למכונות וירטואליות עם GPU:

  1. במסוף Google Cloud , נכנסים לדף תבניות של הגדרות מכונה.

    כניסה לדף Instance templates

  2. לוחצים על יצירת תבנית של הגדרות מכונה.

  3. בשדה Name, נותנים שם לתבנית של הגדרות המכונה.

  4. בקטע מיקום בוחרים אחת מהאפשרויות הבאות:

    • כדי ליצור תבנית גלובלית של הגדרות מכונה, בוחרים באפשרות Global (ברירת המחדל).

    • כדי ליצור תבנית של הגדרות מכונה אזורית, בוחרים באפשרות Regional ואז בוחרים את האזור שבו רוצים ליצור את התבנית.

  5. בקטע Machine configuration מבצעים את הפעולות הבאות:

    1. לוחצים על הכרטיסייה GPUs.

    2. בתפריט GPU type, בוחרים את סוג ה-GPU.

    3. בתפריט Number of GPUs, בוחרים את מספר ה-GPU.

    4. אופציונלי: אם דגם ה-GPU תומך ב-NVIDIA RTX Virtual Workstations (vWS)‎ לעומסי עבודה של גרפיקה, ואתם מתכננים להריץ עומסי עבודה שדורשים הרבה משאבי גרפיקה, בחרו באפשרות Enable Virtual Workstation (NVIDIA GRID)‎.

    5. בקטע Machine type, בוחרים סוג מכונה.

  6. אופציונלי: כדי לשנות את ערך ברירת המחדל של סוג דיסק האתחול או התמונה, בקטע Boot disk לוחצים על Change. לאחר מכן, פועלים לפי ההנחיות כדי לשנות את דיסק האתחול.

  7. לוחצים על יצירה.

gcloud

כדי ליצור תבנית של הגדרות מכונה ל-VM עם GPU, משתמשים בפקודה instance-templates create ומגדירים את הדגל --maintenance-policy לערך TERMINATE.

לדוגמה, כדי ליצור תבנית גלובלית של הגדרות מכונה ל-GPU VMs, משתמשים בפקודה הבאה:

gcloud compute instance-templates create INSTANCE_TEMPLATE_NAME \
    --image-project=IMAGE_PROJECT \
    --image-family=IMAGE_FAMILY \
    --machine-type=MACHINE_TYPE \
    --maintenance-policy=TERMINATE

מחליפים את מה שכתוב בשדות הבאים:

  • ‫INSTANCE_TEMPLATE_NAME: השם של התבנית של הגדרות המכונה.

  • ‫IMAGE_PROJECT: פרויקט התמונה שמכיל את התמונה, לדוגמה debian-cloud. למידע נוסף על פרויקטים של תמונות נתמכות, ראו תמונות ציבוריות.

  • ‫IMAGE_FAMILY או IMAGE: מציינים אחת מהאפשרויות הבאות:

    • ‫IMAGE_FAMILY: משפחת קובצי אימג'. כך מציינים את קובץ אימג' של מערכת ההפעלה העדכני ביותר, שלא הוצא משימוש. לדוגמה, אם מציינים את הערך debian-13, המערכת משתמשת בגרסה העדכנית במשפחת קובצי האימג' של Debian 13. למידע נוסף על השימוש במשפחות של קובצי אימג', ראו שיטות מומלצות למשפחות של קובצי אימג'.

    • ‫IMAGE: גרסה ספציפית של קובץ האימג' של מערכת ההפעלה, לדוגמה debian-13-trixie-v20260902. אם בוחרים לציין גרסה ספציפית של קובץ האימג' של מערכת ההפעלה, צריך להחליף את הדגל --image-family בדגל --image.

  • ‫MACHINE_TYPE: סוג המכונה של המכונות הווירטואליות. אם מציינים סוג מכונה N1, צריך לכלול את הדגל --accelerator כדי לציין את המספר והסוג של יחידות ה-GPU שרוצים לצרף למכונות הווירטואליות.

לדוגמה, נניח שרוצים ליצור תבנית גלובלית של הגדרות מכונה למכונות וירטואליות של GPU, עם המאפיינים הבאים:

  • מכונה עם קונפיגורציה מוגדרת (predefined) מסוג N1 עם 2 יחידות vCPU.

  • מעבד גרפי אחד מסוג NVIDIA T4 לחיבור למכונות הווירטואליות.

  • ‫Debian כפרויקט של קובץ האימג'.

  • ‫Debian 13 כמשפחת קובצי האימג'.

כדי ליצור את התבנית של הגדרות המכונה לדוגמה, משתמשים בפקודה הבאה:

gcloud compute instance-templates create instance-template-gpu \
    --accelerator=count=1,type=nvidia-tesla-t4 \
    --machine-type=n1-standard-2 \
    --image-family=debian-13 \
    --image-project=debian-cloud \
    --maintenance-policy=TERMINATE

Terraform

כדי ליצור תבנית של הגדרות מכונה, אפשר להשתמש באחד מהמשאבים הבאים:

בדוגמה הבאה נוצרת תבנית גלובלית של הגדרות מכונה, שמציינת מכונה עם קונפיגורציה מוגדרת (predefined) מסוג N1 עם 2 מעבדי vCPU ומעבד גרפי אחד מסוג NVIDIA T4 שמחובר אליה:

resource "google_compute_instance_template" "default" {
  name         = "gpu-template"
  machine_type = "n1-standard-2"

  disk {
    source_image = "debian-cloud/debian-13"
  }

  network_interface {
    network = "default"
  }

  guest_accelerator {
    type  = "nvidia-tesla-t4"
    count = 1
  }

  scheduling {
    on_host_maintenance = "TERMINATE"
  }
}

כדי ללמוד איך להחיל הגדרות ב-Terraform או להסיר אותן, ראו פקודות בסיסיות ב-Terraform.

REST

כדי ליצור תבנית של הגדרות מכונה ל-VM עם GPU, שולחים בקשת POST ל-method‏ instanceTemplates.insert. בגוף הבקשה, כוללים את השדה onHostMaintenance ומגדירים אותו לערך TERMINATE.

לדוגמה, כדי ליצור תבנית גלובלית של הגדרות מכונה ל-VM עם GPU, שולחים בקשת POST באופן הבא:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/instanceTemplates

{
  "name": "INSTANCE_TEMPLATE_NAME",
  "properties": {
    "disks": [
      {
        "type": "PERSISTENT",
        "boot": true,
        "mode": "READ_WRITE",
        "initializeParams": {
          "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"
        }
      }
    ],
    "machineType": "MACHINE_TYPE",
    "networkInterfaces": [
      {
        "accessConfigs": [
          {
            "name": "external-IP",
            "type": "ONE_TO_ONE_NAT"
          }
        ],
        "network": "global/networks/default"
      }
    ],
    "scheduling": {
      "onHostMaintenance": "TERMINATE"
    }
  }
}

מחליפים את מה שכתוב בשדות הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט שבו רוצים ליצור את התבנית של הגדרות המכונה.

  • ‫INSTANCE_TEMPLATE_NAME: השם של התבנית של הגדרות המכונה.

  • ‫IMAGE_PROJECT: פרויקט התמונה שמכיל את התמונה, לדוגמה debian-cloud. למידע נוסף על פרויקטים של תמונות נתמכות, ראו תמונות ציבוריות.

  • ‫IMAGE או IMAGE_FAMILY: מציינים אחת מהאפשרויות הבאות:

    • ‫IMAGE: גרסה ספציפית של קובץ האימג' של מערכת ההפעלה, לדוגמה debian-13-trixie-v20260902.

    • ‫IMAGE_FAMILY: משפחת קובצי אימג'. כך מציינים את קובץ אימג' של מערכת ההפעלה העדכני ביותר, שלא הוצא משימוש. לדוגמה, אם מציינים את הערך family/debian-13, המערכת משתמשת בגרסה העדכנית במשפחת קובצי האימג' של Debian 13. למידע נוסף על השימוש במשפחות של קובצי אימג', ראו שיטות מומלצות למשפחות של קובצי אימג'.

  • ‫MACHINE_TYPE: סוג המכונה של המכונות הווירטואליות. אם מציינים סוג מכונה N1, צריך לכלול את השדה guestAccelerators כדי לציין את המספר והסוג של יחידות ה-GPU שרוצים לצרף למכונות הווירטואליות.

לדוגמה, נניח שרוצים ליצור תבנית גלובלית של הגדרות מכונה למכונות וירטואליות של GPU, עם המאפיינים הבאים:

  • מכונה עם קונפיגורציה מוגדרת (predefined) מסוג N1 עם 2 יחידות vCPU.

  • מעבד גרפי אחד מסוג NVIDIA T4 לחיבור למכונות הווירטואליות.

  • ‫Debian כפרויקט של קובץ האימג'.

  • ‫Debian 13 כמשפחת קובצי האימג'.

כדי ליצור את תבנית של הגדרות המכונה לדוגמה, שולחים בקשת POST באופן הבא:

POST https://compute.googleapis.com/compute/v1/projects/example-project/global/instanceTemplates

{
  "name": "instance-template-gpu",
  "properties": {
    "disks": [
      {
        "type": "PERSISTENT",
        "boot": true,
        "mode": "READ_WRITE",
        "initializeParams": {
          "sourceImage": "projects/debian-cloud/global/images/family/debian-13"
        }
      }
    ],
    "guestAccelerators": [
      {
        "acceleratorType": "nvidia-tesla-t4",
        "acceleratorCount": 1
      }
    ],
    "machineType": "n1-standard-2",
    "networkInterfaces": [
      {
        "accessConfigs": [
          {
            "name": "external-IP",
            "type": "ONE_TO_ONE_NAT"
          }
        ],
        "network": "global/networks/default"
      }
    ],
    "scheduling": {
      "onHostMaintenance": "TERMINATE"
    }
  }
}

אפשרויות הגדרה נוספות ליצירת תבנית של הגדרות מכונה מפורטות בקטע יצירת תבנית של הגדרות מכונה שבמסמך הזה.

יצירת תבנית של הגדרות מכונה עם קובץ אימג' של קונטיינר

אפשר לציין קובץ אימג' של קונטיינר בתבנית של הגדרות מכונה. כברירת מחדל, Compute Engine כולל בתבנית גם קובץ אימג' של מערכת הפעלה שמותאמת לקונטיינרים עם Docker מותקן. כשמשתמשים בתבנית כדי ליצור מכונה חדשה, הקונטיינר מופעל באופן אוטומטי כשהמכונה מופעלת.

המסוף

  1. נכנסים לדף Instance templates.

    כניסה לדף Instance templates

  2. לוחצים על יצירת תבנית של הגדרות מכונה.

  3. בקטע Container (מאגר תגים), לוחצים על Deploy Container (פריסת מאגר תגים).

  4. בתיבת הדו-שיח Configure container, מציינים את קובץ האימג' של הקונטיינר שבו רוצים להשתמש.

    • אפשר לציין קובץ אימג' מ-Container Registry או מ-Artifact Registry. לדוגמה:
      • gcr.io/cloud-marketplace/google/nginx1:TAG, כאשר TAG הוא התג שהוגדר לגרסה ספציפית של קובץ אימג' של קונטיינר NGINX שזמין ב-Google Cloud Marketplace.
      • ‫us-docker.pkg.dev/google-samples/containers/gke/hello-app:1.0 בוחרת תמונה לדוגמה של hello-app שמאוחסנת ב-Artifact Registry.
    • אם אתם משתמשים בקובץ אימג' של קונטיינר מ-Docker Hub, תמיד ציינו את השם המלא של קובץ האימג' של Docker. לדוגמה, כדי לפרוס קובץ אימג' של קונטיינר Apache, מציינים את שם קובץ האימג' הבא: docker.io/httpd:2.4.
  5. אם רוצים, לוחצים על אפשרויות מתקדמות של מאגר התגים. למידע נוסף, קראו את המאמר הגדרת אפשרויות להרצת קונטיינר.

  6. לוחצים על יצירה.

gcloud

משתמשים בפקודה gcloud compute instance-templates create-with-container:

 gcloud compute instance-templates create-with-container INSTANCE_TEMPLATE_NAME \
     --container-image=CONTAINER_IMAGE

מחליפים את מה שכתוב בשדות הבאים:

  • ‫INSTANCE_TEMPLATE_NAME: השם של התבנית שרוצים ליצור.
  • ‫CONTAINER_IMAGE: השם המלא של קובץ האימג' של הקונטיינר שבו רוצים להשתמש.

לדוגמה, הפקודה הבאה יוצרת תבנית חדשה של הגדרות מכונה בשם nginx-vm. מכונה וירטואלית שנוצרה מהתבנית הזו מפעילה ומריצה את קובץ האימג' של הקונטיינר, gcr.io/cloud-marketplace/google/nginx1:TAG, כשהמכונה הווירטואלית מופעלת.

 gcloud compute instance-templates create-with-container nginx-vm \
     --container-image=gcr.io/cloud-marketplace/google/nginx1:TAG

מחליפים את TAG בתג שהוגדר לגרסה ספציפית של קובץ האימג' של קונטיינר NGINX שזמין ב-Google Cloud Marketplace.

אתם יכולים גם להגדיר אפשרויות להרצת הקונטיינר.

יצירת תבנית של הגדרות מכונה שמציינת תת-רשת

gcloud

כדי ליצור תבנית של הגדרות מכונה אזורית או גלובלית, משתמשים בפקודה instance-templates create. משתמשים בדגל --subnet כדי להציב מכונות שנוצרו מהתבנית ברשת המשנה הרצויה. הדגל --subnet מחייב את הדגל --region.

אם רוצים ליצור תבנית של הגדרות מכונה אזורית, צריך להשתמש בדגל --instance-template-region כדי להגדיר את האזור של התבנית. חשוב לוודא שאתם משתמשים בתת-רשת מאותו אזור שבו אתם רוצים ליצור את התבנית של הגדרות המכונה האזורית.

gcloud compute instance-templates create INSTANCE_TEMPLATE_NAME \
    --region=REGION \
    --subnet=SUBNET_NAME_OR_URL \
    --stack-type=STACK_TYPE \
    --instance-template-region=INSTANCE_TEMPLATE_REGION

מחליפים את מה שכתוב בשדות הבאים:

  • ‫INSTANCE_TEMPLATE_NAME: השם של התבנית של הגדרות המכונה
  • ‫REGION: האזור של תת-הרשת
  • ‫SUBNET_NAME_OR_URL: השם של תת-הרשת או כתובת ה-URL שלה

  • ‫STACK_TYPE: אופציונלי: אם IPv6 מופעל בממשק הרשת שמוגדר כברירת מחדל. אפשר להשתמש בערכים הבאים: IPV4_ONLY,‏ IPV4_IPV6 או IPV6_ONLY. אם לא כוללים את הדגל הזה, ערך ברירת המחדל הוא IPV4_ONLY.

  • ‫INSTANCE_TEMPLATE_REGION: האזור שבו רוצים ליצור את התבנית של הגדרות המכונה. האזור הזה צריך להיות זהה לאזור של REGION.

בדוגמה הבאה נוצרת תבנית בשם template-qa שיוצרת מכונות רק ברשת המשנה subnet-us-qa.

gcloud compute instance-templates create template-qa \
    --region=us-central1 \
    --subnet=subnet-us-qa

הפלט אמור להיראות כך:

Created [https://compute.googleapis.com/compute/latest/projects/PROJECT_ID/global/instanceTemplates/template-qa].
NAME        MACHINE_TYPE        PREEMPTIBLE CREATION_TIMESTAMP
template-qa e2-standard-2       2019-12-23T20:34:00.791-07:00

המשך

import (
	"context"
	"fmt"
	"io"

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

// createTemplateWithSubnet creates an instance template that uses a provided subnet.
func createTemplateWithSubnet(w io.Writer, projectID, network, subnetwork, templateName string) error {
	// projectID := "your_project_id"
	// network := "projects/project/global/networks/network"
	// subnetwork := "projects/project/regions/region/subnetworks/subnetwork"
	// templateName := "your_template_name"

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

	req := &computepb.InsertInstanceTemplateRequest{
		Project: projectID,
		InstanceTemplateResource: &computepb.InstanceTemplate{
			Name: proto.String(templateName),
			Properties: &computepb.InstanceProperties{
				// The template describes the size and source image of the boot disk
				// to attach to the instance.
				Disks: []*computepb.AttachedDisk{
					{
						InitializeParams: &computepb.AttachedDiskInitializeParams{
							DiskSizeGb:  proto.Int64(250),
							SourceImage: proto.String("projects/debian-cloud/global/images/family/debian-12"),
						},
						AutoDelete: proto.Bool(true),
						Boot:       proto.Bool(true),
					},
				},
				MachineType: proto.String("e2-standard-4"),
				// The template connects the instance to the specified network and subnetwork.
				NetworkInterfaces: []*computepb.NetworkInterface{
					{
						Network:    proto.String(network),
						Subnetwork: proto.String(subnetwork),
					},
				},
			},
		},
	}

	op, err := instanceTemplatesClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create instance template: %w", err)
	}

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

	fmt.Fprintf(w, "Instance template 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.GlobalOperationsClient;
import com.google.cloud.compute.v1.InsertInstanceTemplateRequest;
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.NetworkInterface;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateTemplateWithSubnet {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    /*
    TODO(developer): Replace these variables before running the sample.
    projectId: project ID or project number of the Cloud project you use.
    network: the network to be used in the new template. This value uses
        the following format: "projects/{project}/global/networks/{network}"
    subnetwork: the subnetwork to be used in the new template. This value
        uses the following format: "projects/{project}/regions/{region}/subnetworks/{subnetwork}"
    templateName: name of the new template to create.
    */
    String projectId = "your-project-id";
    String network = String.format("projects/%s/global/networks/%s", projectId, "network");
    String subnetwork = String.format("projects/%s/regions/%s/subnetworks/%s", projectId, "region",
        "subnetwork");
    String templateName = "template-name";
    createTemplateWithSubnet(projectId, network, subnetwork, templateName);
  }

  // Create an instance template that uses a provided subnet.
  public static void createTemplateWithSubnet(String projectId, String network, String subnetwork,
      String templateName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    try (InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create();
        GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.create()) {

      AttachedDisk disk = AttachedDisk.newBuilder()
          .setInitializeParams(AttachedDiskInitializeParams.newBuilder()
              .setSourceImage(
                  String.format("projects/%s/global/images/family/%s", "debian-cloud", "debian-13"))
              .setDiskSizeGb(250).build())
          .setAutoDelete(true)
          .setBoot(true)
          .build();

      InstanceProperties instanceProperties = InstanceProperties.newBuilder()
          .addDisks(disk)
          .setMachineType("e2-standard-4")
          .addNetworkInterfaces(NetworkInterface.newBuilder()
              .setNetwork(network)
              .setSubnetwork(subnetwork).build())
          .build();

      InstanceTemplate instanceTemplate = InstanceTemplate.newBuilder()
          .setName(templateName)
          .setProperties(instanceProperties)
          .build();

      InsertInstanceTemplateRequest insertInstanceTemplateRequest = InsertInstanceTemplateRequest
          .newBuilder()
          .setProject(projectId)
          .setInstanceTemplateResource(instanceTemplate)
          .build();

      Operation operation = instanceTemplatesClient.insertCallable()
          .futureCall(insertInstanceTemplateRequest).get(3, TimeUnit.MINUTES);

      Operation response = globalOperationsClient.wait(projectId, operation.getName());

      if (response.hasError()) {
        System.out.println("Template creation from subnet failed ! ! " + response);
        return;
      }
      System.out.printf("Template creation from subnet operation status %s: %s", templateName,
          response.getStatus());
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const network = 'projects/project/global/networks/network';
// const subnetwork = 'projects/project/regions/region/subnetworks/subnetwork';
// const templateName = 'your_template_name';

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

// Create an instance template that uses a provided subnet.
async function createTemplateWithSubnet() {
  const instanceTemplatesClient = new compute.InstanceTemplatesClient();

  const [response] = await instanceTemplatesClient.insert({
    project: projectId,
    instanceTemplateResource: {
      name: templateName,
      properties: {
        // The template describes the size and source image of the boot disk
        // to attach to the instance.
        disks: [
          {
            // The template describes the size and source image of the boot disk
            // to attach to the instance.
            initializeParams: {
              diskSizeGb: '250',
              sourceImage:
                'projects/debian-cloud/global/images/family/debian-13',
            },
            autoDelete: true,
            boot: true,
          },
        ],
        machineType: 'e2-standard-4',
        // The template connects the instance to the specified network and subnetwork.
        networkInterfaces: [
          {
            network,
            subnetwork,
          },
        ],
      },
    },
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.GlobalOperationsClient();

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

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

createTemplateWithSubnet();

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_template_with_subnet(
    project_id: str, network: str, subnetwork: str, template_name: str
) -> compute_v1.InstanceTemplate:
    """
    Create an instance template that uses a provided subnet.

    Args:
        project_id: project ID or project number of the Cloud project you use.
        network: the network to be used in the new template. This value uses
            the following format: "projects/{project}/global/networks/{network}"
        subnetwork: the subnetwork to be used in the new template. This value
            uses the following format: "projects/{project}/regions/{region}/subnetworks/{subnetwork}"
        template_name: name of the new template to create.

    Returns:
        InstanceTemplate object that represents the new instance template.
    """
    # The template describes the size and source image of the book disk to
    # attach to the instance.
    disk = compute_v1.AttachedDisk()
    initialize_params = compute_v1.AttachedDiskInitializeParams()
    initialize_params.source_image = (
        "projects/debian-cloud/global/images/family/debian-13"
    )
    initialize_params.disk_size_gb = 250
    disk.initialize_params = initialize_params
    disk.auto_delete = True
    disk.boot = True

    template = compute_v1.InstanceTemplate()
    template.name = template_name
    template.properties = compute_v1.InstanceProperties()
    template.properties.disks = [disk]
    template.properties.machine_type = "e2-standard-4"

    # The template connects the instance to the specified network and subnetwork.
    network_interface = compute_v1.NetworkInterface()
    network_interface.network = network
    network_interface.subnetwork = subnetwork
    template.properties.network_interfaces = [network_interface]

    template_client = compute_v1.InstanceTemplatesClient()
    operation = template_client.insert(
        project=project_id, instance_template_resource=template
    )
    wait_for_extended_operation(operation, "instance template creation")

    return template_client.get(project=project_id, instance_template=template_name)

אם משתמשים בתבנית הזו כדי ליצור מכונות ל-MIG (עם או בלי התאמה לעומס (autoscaling)), המכונה נוצרת באופן אוטומטי באזור וב-subnet שצוינו. כך אפשר לשלוט בתת-הרשת של מכונות חדשות שנוצרו לאיזון עומסים.

שימוש בתמונות בהתאמה אישית או בתמונות ציבוריות בתבניות של הגדרות מכונה

אתם יכולים להשתמש בתמונה בהתאמה אישית או בתמונה ציבורית לתבניות של הגדרות המכונה:

  • תמונות בהתאמה אישית. מכיוון שקבוצות MIG מיועדות להוספה ולהסרה של מכונות לעיתים קרובות, כדאי ליצור קובץ אימג' בהתאמה אישית ולציין אותו בתבנית של הגדרות המכונה. אתם יכולים להכין את קובץ האימג' עם האפליקציות וההגדרות שהמכונות הווירטואליות צריכות, כדי שלא תצטרכו להגדיר אותן ידנית בכל מכונה וירטואלית בנפרד בקבוצת ה-MIG.

  • תמונות ציבוריות. אפשר ליצור תבנית של הגדרות מכונה שמשתמשת בתמונה שזמינה לכולם ובסקריפט לטעינה בזמן ההפעלה כדי להכין את המכונה אחרי שהיא מתחילה לפעול.

תמונות בהתאמה אישית הן יותר דטרמיניסטיות ומתחילות מהר יותר ממכונות וירטואליות עם סקריפטים לטעינה בזמן ההפעלה. עם זאת, סקריפטים לטעינה בזמן ההפעלה הם גמישים יותר, מה שעוזר לעדכן את האפליקציות וההגדרות במכונות.

אם אתם מנהלים קובצי אימג' באמצעות משפחות של קובצי אימג', אתם יכולים לציין את השם של משפחת קובצי האימג' הציבורית או המותאמת אישית בתבנית של הגדרות המכונה. למידע נוסף על משפחות של קובצי אימג', קראו את השיטות המומלצות לשימוש במשפחות של קובצי אימג' ב-Compute Engine.

המאמרים הבאים