שימוש בהזמנות

במאמר הזה מוסבר איך להשתמש בהזמנות ב-Compute Engine. כדי ללמוד איך להשתמש בהזמנות במוצרי Google Cloud Google אחרים, אפשר לעיין במסמכים הבאים:

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

מגבלות

אי אפשר להשתמש בשמירת מקום כדי ליצור את המשאבים הבאים של Compute Engine:

  • Flex-start VMs

  • מכונות וירטואליות במודל Spot או מופעים זמניים שניתנים להפסקה

  • שרתים לדייר יחיד (sole-tenant)

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

התפקידים הנדרשים

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

  • כדי לצרוך מקום שמור: Compute Instance Admin (v1) (roles/compute.instanceAdmin.v1) בפרויקט
  • כדי לצרוך מקום שמור משותף מפרויקט צרכן: Compute Instance Admin (v1) (roles/compute.instanceAdmin.v1) בפרויקט הבעלים ובפרויקט הצרכן

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

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

ההרשאות הנדרשות

כדי להשתמש בהזמנות, צריך את ההרשאות הבאות:

  • כדי ליצור הזמנות: compute.reservations.create בפרויקט
  • כדי ליצור מופעים:
    • compute.instances.create בפרויקט
    • כדי להשתמש באימג' בהתאמה אישית ליצירת המכונה הווירטואלית (VM): compute.images.useReadOnly בקובץ אימג'
    • כדי להשתמש ב-snapshot ליצירת המכונה הווירטואלית: compute.snapshots.useReadOnly בקובץ ה-snapshot
    • כדי להשתמש בתבנית של הגדרות מכונה ליצירת המכונה הווירטואלית: compute.instanceTemplates.useReadOnly בתבנית של הגדרות המכונה
    • כדי להקצות רשת מדור קודם למכונה הווירטואלית: compute.networks.use בפרויקט
    • כדי לציין כתובת IP סטטית למכונה הווירטואלית: compute.addresses.use בפרויקט
    • כדי להקצות כתובת IP חיצונית למכונה הווירטואלית כשמשתמשים ברשת מדור קודם: compute.networks.useExternalIp בפרויקט
    • כדי לציין רשת משנה למכונה הווירטואלית: compute.subnetworks.use בפרויקט או ברשת המשנה שנבחרה
    • כדי להקצות כתובת IP חיצונית למכונה הווירטואלית כשמשתמשים ברשת VPC: compute.subnetworks.useExternalIp בפרויקט או ברשת המשנה שנבחרה
    • כדי להגדיר מטא-נתונים של המכונה הווירטואלית למכונה הווירטואלית: compute.instances.setMetadata בפרויקט
    • כדי להגדיר תגים למכונה הווירטואלית: compute.instances.setTags במכונה הווירטואלית
    • כדי להגדיר תוויות למכונה הווירטואלית: compute.instances.setLabels במכונה הווירטואלית
    • כדי להגדיר חשבון שירות לשימוש של המכונה הווירטואלית: compute.instances.setServiceAccount במכונה הווירטואלית
    • כדי ליצור דיסק חדש למכונה הווירטואלית: compute.disks.create בפרויקט
    • כדי לצרף דיסק קיים במצב קריאה-בלבד או במצב קריאה וכתיבה: compute.disks.use בדיסק
    • כדי לצרף דיסק קיים במצב קריאה-בלבד: compute.disks.useReadOnly בדיסק
  • כדי ליצור תבניות של מכונות: ‫compute.instanceTemplates.create בפרויקט

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

שימוש בהזמנה

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

כדי להשתמש בהזמנה, אפשר להשתמש באחת מהשיטות הבאות:

שימוש בהזמנה שנעשה בה שימוש באופן אוטומטי

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

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

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

המסוף

בדוגמה הבאה אפשר לראות איך ליצור הזמנה אוטומטית באזור us-central1-a לשלוש מכונות N2 עם 32 מעבדי CPU וירטואליים, ו-Intel Cascade Lake כפלטפורמת ה-CPU המינימלית. בנוסף, מוסבר איך ליצור מופע יחיד כדי להשתמש בהזמנה.

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

  1. כדי ליצור הזמנה לדוגמה, מבצעים את השלבים הבאים:

    1. פותחים את הדף Reservations במסוף Google Cloud .

      כניסה לדף Reservations

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

    2. בכרטיסייה מקום שמור על פי דרישה (ברירת המחדל), לוחצים על ‎ יצירת מקום שמור. ייפתח הדף Create a reservation.

    3. בשדה Name, מזינים שם להזמנה. לדוגמה, מזינים reservation-01.

    4. בוחרים את האזור והתחום שבהם רוצים לשמור מקום למשאבים. לדוגמה, בוחרים באפשרות us-central1 ובאפשרות us-central1-a בהתאמה.

    5. בקטע Share type, מבצעים אחת מהפעולות הבאות:

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

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

    6. בקטע Use with VM instance, מסמנים את האפשרות Use reservation automatically (אם היא עדיין לא מסומנת).

    7. בשדה Number of VM instances (מספר מכונות ה-VM), מזינים את הערך 3.

    8. בכרטיסייה לשימוש כללי, בוחרים באפשרות N2.

    9. בקטע סוג מכונה, בכרטיסייה Preset (ברירת מחדל), בוחרים באפשרות n2-standard-32.

    10. מרחיבים את האפשרות CPU platform and GPU (פלטפורמת מעבד ו-GPU) ואז בשדה CPU platform (פלטפורמת מעבד) בוחרים באפשרות Intel Cascade Lake or later (פלטפורמת מעבד Intel Cascade Lake או גרסה מתקדמת יותר).

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

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

    1. נכנסים לדף Create an instance במסוף Google Cloud .

      כניסה לדף Create an instance

      הדף Create an instance מופיע ובו החלונית Machine configuration.

    2. בחלונית Machine configuration (הגדרת המכונה):

      1. בשדה Name, מזינים שם למופע. בדוגמה הזו, מזינים instance-01.

      2. מציינים את האזור והתחום שבהם רוצים לשמור מקום למשאבים. לצורך הדוגמה הזו, בוחרים באפשרויות us-central1 ו-us-central1-a.

      3. בכרטיסייה לשימוש כללי, בוחרים באפשרות N2.

      4. בקטע סוג מכונה, בכרטיסייה Preset (ברירת מחדל), בוחרים באפשרות n2-standard-32.

      5. מרחיבים את הקטע אפשרויות מתקדמות, ואז בשדה פלטפורמת CPU בוחרים באפשרות Intel Cascade Lake או גרסה מתקדמת יותר.

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

      1. בתפריט הניווט, לוחצים על מתקדם. מופיעה החלונית Advanced.

      2. בקטע Reservations, בוחרים באפשרות Use automatic selection.

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

gcloud

בדוגמה הבאה אפשר לראות איך ליצור הזמנה אוטומטית באזור us-central1-a לשלוש מכונות N2 עם 32 מעבדי CPU וירטואליים, ו-Intel Cascade Lake כפלטפורמת ה-CPU המינימלית. בנוסף, מוסבר איך ליצור מופע יחיד כדי להשתמש בהזמנה.

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

  1. כדי ליצור את ההזמנה לדוגמה, משתמשים בפקודה gcloud compute reservations create:

    gcloud compute reservations create reservation-01 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --vm-count=3 \
        --zone=us-central1-a
    
  2. כדי ליצור מכונה שצורכת את ההזמנה לדוגמה, משתמשים בפקודה gcloud compute instances create עם הדגל --reservation-affinity שהערך שלו הוא any. אפשר גם להשמיט את הדגל הזה כי any היא הגדרת ברירת המחדל.

    gcloud compute instances create instance-01 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --reservation-affinity=any \
        --zone=us-central1-a
    

המשך

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

import (
	"context"
	"fmt"
	"io"

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

// consumeAnyReservation creates instance, consuming any available reservation
func consumeAnyReservation(w io.Writer, projectID, zone, instanceName, sourceTemplate string) error {
	// projectID := "your_project_id"
	// zone := "us-west3-a"
	// instanceName := "your_instance_name"
	// sourceTemplate: existing template path. Following formats are allowed:
	//  	- projects/{project_id}/global/instanceTemplates/{template_name}
	//  	- projects/{project_id}/regions/{region}/instanceTemplates/{template_name}
	//  	- https://www.googleapis.com/compute/v1/projects/{project_id}/global/instanceTemplates/instanceTemplate
	//  	- https://www.googleapis.com/compute/v1/projects/{project_id}/regions/{region}/instanceTemplates/instanceTemplate

	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,
		SourceInstanceTemplate: proto.String(sourceTemplate),
		InstanceResource: &computepb.Instance{
			Name: proto.String(instanceName),
			// specifies that any matching reservation should be consumed
			ReservationAffinity: &computepb.ReservationAffinity{
				ConsumeReservationType: proto.String("ANY_RESERVATION"),
			},
		},
	}

	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 from reservation\n")

	return nil
}

Java

בדוגמה הבאה מוצג אופן היצירה של מכונת N1 עם ארבעה מעבדי CPU וירטואליים, ו-Intel Skylake כפלטפורמת ה-CPU המינימלית באזור us-central1-a. המופע משתמש אוטומטית בהזמנה תואמת.

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

import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.ANY_RESERVATION;

import com.google.api.gax.longrunning.OperationFuture;
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.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.ReservationAffinity;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ConsumeAnyMatchingReservation {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Zone where the VM instance will be created.
    String zone = "us-central1-a";
    // Name of the VM instance you want to query.
    String instanceName = "YOUR_INSTANCE_NAME";
    // machineType: machine type of the VM being created.
    // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
    String machineTypeName = "n1-standard-4";
    // sourceImage: path to the operating system image to mount.
    // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
    String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
    // diskSizeGb: storage size of the boot disk to attach to the instance.
    long diskSizeGb = 10L;
    // networkName: network interface to associate with the instance.
    String networkName = "default";
    // Minimum CPU platform of the instances.
    String minCpuPlatform = "Intel Skylake";

    createInstanceAsync(projectId, zone, instanceName, machineTypeName, sourceImage,
        diskSizeGb, networkName, minCpuPlatform);
  }

  // Create a virtual machine targeted with the reserveAffinity field.
  // In this consumption model, existing and new VMs automatically consume a reservation
  // if their properties match the VM properties specified in the reservation.
  public static Instance createInstanceAsync(String projectId, String zone,
      String instanceName, String machineTypeName, String sourceImage,
      long diskSizeGb, String networkName, String minCpuPlatform)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    String machineType = String.format("zones/%s/machineTypes/%s", zone, machineTypeName);
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (InstancesClient instancesClient = InstancesClient.create()) {
      AttachedDisk disk =
          AttachedDisk.newBuilder()
              .setBoot(true)
              .setAutoDelete(true)
              .setType(AttachedDisk.Type.PERSISTENT.toString())
              .setDeviceName("disk-1")
              .setInitializeParams(
                  AttachedDiskInitializeParams.newBuilder()
                      .setSourceImage(sourceImage)
                      .setDiskSizeGb(diskSizeGb)
                      .build())
              .build();

      NetworkInterface networkInterface = NetworkInterface.newBuilder()
          .setName(networkName)
          .build();

      ReservationAffinity reservationAffinity =
          ReservationAffinity.newBuilder()
              .setConsumeReservationType(ANY_RESERVATION.toString())
              .build();

      Instance instanceResource =
          Instance.newBuilder()
              .setName(instanceName)
              .setMachineType(machineType)
              .addDisks(disk)
              .addNetworkInterfaces(networkInterface)
              .setMinCpuPlatform(minCpuPlatform)
              .setReservationAffinity(reservationAffinity)
              .build();

      InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setInstanceResource(instanceResource)
          .build();

      OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
          insertInstanceRequest);

      Operation response = operation.get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        return null;
      }
      return instancesClient.get(projectId, zone, instanceName);
    }
  }
}

Node.js

בדוגמה הבאה מוצג אופן היצירה של מכונת N1 עם ארבעה מעבדי CPU וירטואליים, ו-Intel Skylake כפלטפורמת ה-CPU המינימלית באזור us-central1-a. המופע משתמש אוטומטית בהזמנה תואמת.

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

// Import the Compute library
const computeLib = require('@google-cloud/compute');
const compute = computeLib.protos.google.cloud.compute.v1;

// Instantiate a reservationsClient
const instancesClient = new computeLib.InstancesClient();
// Instantiate a zoneOperationsClient
const zoneOperationsClient = new computeLib.ZoneOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The ID of the project where you want to create instance.
const projectId = await instancesClient.getProjectId();
// The zone in which to create instance.
const zone = 'us-central1-a';
// The name of the instance to create.
// const instanceName = 'instance-01';
// Machine type to use for VM.
const machineType = 'n1-standard-4';

// Create instance to consume reservation if their properties match the VM properties
async function callCreateInstanceToConsumeAnyReservation() {
  // Describe the size and source image of the boot disk to attach to the instance.
  const disk = new compute.Disk({
    boot: true,
    autoDelete: true,
    type: 'PERSISTENT',
    initializeParams: {
      diskSizeGb: '10',
      sourceImage: 'projects/debian-cloud/global/images/family/debian-12',
    },
  });

  //  Define networkInterface
  const networkInterface = new compute.NetworkInterface({
    name: 'global/networks/default',
  });

  // Define reservationAffinity
  const reservationAffinity = new compute.ReservationAffinity({
    consumeReservationType: 'ANY_RESERVATION',
  });

  // Create an instance
  const instance = new compute.Instance({
    name: instanceName,
    machineType: `zones/${zone}/machineTypes/${machineType}`,
    minCpuPlatform: 'Intel Skylake',
    disks: [disk],
    networkInterfaces: [networkInterface],
    reservationAffinity,
  });

  const [response] = await instancesClient.insert({
    project: projectId,
    instanceResource: instance,
    zone,
  });

  let operation = response.latestResponse;

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

  console.log(`Instance ${instanceName} created.`);
}

await callCreateInstanceToConsumeAnyReservation();

Python

בדוגמה הבאה מוצג איך ליצור מקום שמור אוטומטי בתחום (zone) us-central1-a לשלוש מכונות N1 עם vCPU אחד, ו-Intel Ivy כפלטפורמת CPU מינימלית. בנוסף, מוסבר איך ליצור מופע יחיד כדי להשתמש בהזמנה.

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

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 consume_any_project_reservation(
    project_id: str,
    zone: str,
    reservation_name: str,
    instance_name: str,
    machine_type: str = "n1-standard-1",
    min_cpu_platform: str = "Intel Ivy Bridge",
) -> compute_v1.Instance:
    """
    Creates a specific reservation in a single project and launches a VM
    that consumes the newly created reservation.
    Args:
        project_id (str): The ID of the Google Cloud project.
        zone (str): The zone to create the reservation.
        reservation_name (str): The name of the reservation to create.
        instance_name (str): The name of the instance to create.
        machine_type (str): The machine type for the instance.
        min_cpu_platform (str): The minimum CPU platform for the instance.
    """
    instance_properties = (
        compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
            machine_type=machine_type,
            min_cpu_platform=min_cpu_platform,
        )
    )

    reservation = compute_v1.Reservation(
        name=reservation_name,
        specific_reservation=compute_v1.AllocationSpecificSKUReservation(
            count=3,
            instance_properties=instance_properties,
        ),
    )

    # Create a reservation client
    client = compute_v1.ReservationsClient()
    operation = client.insert(
        project=project_id,
        zone=zone,
        reservation_resource=reservation,
    )
    wait_for_extended_operation(operation, "Reservation creation")

    instance = compute_v1.Instance()
    instance.name = instance_name
    instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
    instance.min_cpu_platform = min_cpu_platform
    instance.zone = zone

    # Set the reservation affinity to target any matching reservation
    instance.reservation_affinity = compute_v1.ReservationAffinity(
        consume_reservation_type="ANY_RESERVATION",  # Type of reservation to consume
    )
    # Define the disks for the instance
    instance.disks = [
        compute_v1.AttachedDisk(
            boot=True,  # Indicates that this is a boot disk
            auto_delete=True,  # The disk will be deleted when the instance is deleted
            initialize_params=compute_v1.AttachedDiskInitializeParams(
                source_image="projects/debian-cloud/global/images/family/debian-11",
                disk_size_gb=10,
            ),
        )
    ]
    instance.network_interfaces = [
        compute_v1.NetworkInterface(
            network="global/networks/default",  # The network to use
            access_configs=[
                compute_v1.AccessConfig(
                    name="External NAT",  # Name of the access configuration
                    type="ONE_TO_ONE_NAT",  # Type of access configuration
                )
            ],
        )
    ]
    # Create a request to insert the instance
    request = compute_v1.InsertInstanceRequest()
    request.zone = zone
    request.project = project_id
    request.instance_resource = instance

    vm_client = compute_v1.InstancesClient()
    operation = vm_client.insert(request)
    wait_for_extended_operation(operation, "instance creation")
    print(f"Instance {instance_name} that targets any open reservation created.")

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

REST

בדוגמה הבאה אפשר לראות איך ליצור הזמנה אוטומטית באזור us-central1-a לשלוש מכונות N2 עם 32 מעבדי CPU וירטואליים, ו-Intel Cascade Lake כפלטפורמת ה-CPU המינימלית. בנוסף, מוסבר איך ליצור מופע יחיד כדי להשתמש בהזמנה.

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

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

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations
    
    {
      "name": "reservation-01",
      "specificReservation": {
        "count": "3",
        "instanceProperties": {
          "machineType": "n2-standard-32",
          "minCpuPlatform": "Intel Cascade Lake",
        }
      }
    }
    
  2. כדי ליצור מכונה שצורכת את ההזמנה לדוגמה, שולחים בקשת POST אל ה-method‏ instances.insert. בגוף הבקשה, כוללים את השדה consumeReservationType עם הערך ANY_RESERVATION. עם זאת, מכיוון ש-ANY_RESERVATION הוא הגדרת ברירת המחדל, אפשר גם להשמיט את השדה.

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/instances
    
    {
      "name": "instance-01",
      "machineType": "zones/us-central1-a/machineTypes/n2-standard-32",
      "minCpuPlatform": "Intel Cascade Lake",
      "disks": [
        {
          "boot": true,
          "initializeParams": {
            "sourceImage": "projects/debian-cloud/global/images/family/debian-12"
          }
        }
      ],
      "networkInterfaces": [
        {
          "network": "global/networks/default"
        }
      ],
      "reservationAffinity": {
        "consumeReservationType": "ANY_RESERVATION"
      }
    }
    

שימוש בהזמנה שמטרגטת באופן ספציפי

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

בהתאם לשיטת היצירה שבה רוצים להשתמש, יוצרים הזמנות ספציפיות ומופעים שמיועדים להן באופן הבא:

שיטת יצירה כשיוצרים הזמנה כשיוצרים מכונות שצורכות את ההזמנה
מסוףGoogle Cloud בקטע Use with VM instance, בוחרים באפשרות Select specific reservation. בחלונית Advanced, בקטע Reservations, בוחרים באפשרות Choose a reservation. לאחר מכן פועלים לפי ההנחיות כדי לבחור הזמנה.
Google Cloud CLI כוללים את הדגל --require-specific-reservation. כוללים את הדגלים הבאים:
  • הדגל --reservation-affinity מוגדר לערך specific.
  • הדגל --reservation מוגדר לנתיב המשאב להזמנה, בפורמט projects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
המשך כוללים את השדה SpecificReservationRequired עם הערך true. בשדה ReservationAffinity, כוללים את השדות הבאים:
  • השדה ConsumeReservationType מוגדר לערך SPECIFIC_RESERVATION.
  • השדה Key מוגדר לערך compute.googleapis.com/reservation-name.
  • השדה Values מוגדר לנתיב המשאב להזמנה, בפורמט projects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
Java כוללים את השדה setSpecificReservationRequired עם הערך true. בשדה ReservationAffinity, כוללים את השדות הבאים:
  • השדה setConsumeReservationType מוגדר לערך SPECIFIC_RESERVATION.
  • השדה setKey מוגדר לערך compute.googleapis.com/reservation-name.
  • השדה addValues מוגדר לנתיב המשאב להזמנה, בפורמט projects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
Node.js ו-API בארכיטקטורת REST כוללים את השדה specificReservationRequired עם הערך true. בשדה reservationAffinity, כוללים את השדות הבאים:
  • השדה consumeReservationType מוגדר לערך SPECIFIC_RESERVATION.
  • השדה key מוגדר לערך compute.googleapis.com/reservation-name.
  • השדה values מוגדר לרשימה שמכילה פריט יחיד עם נתיב המשאב להזמנה, בפורמט projects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
Python כוללים את השדה specific_reservation_required עם הערך true. בשדה reservation_affinity, כוללים את השדות הבאים:
  • השדה consume_reservation_type מוגדר לערך SPECIFIC_RESERVATION.
  • השדה key מוגדר לערך compute.googleapis.com/reservation-name.
  • השדה values מוגדר לנתיב המשאב להזמנה, בפורמט projects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
Terraform כוללים את השדה specific_reservation_required עם הערך true. בשדה reservation_affinity, כוללים את השדות הבאים:
  • השדה type מוגדר לערך SPECIFIC_RESERVATION.
  • השדה specific_reservation, שכולל את השדות הבאים:
    • השדה key מוגדר ל-compute.googleapis.com/reservation-name.
    • השדה values מוגדר לרשימה שמכילה פריט יחיד עם נתיב המשאב להזמנה, בפורמט projects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.

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

המסוף

בדוגמה הבאה מוצג איך ליצור הזמנה ספציפית באזור us-central1-a לשלוש מכונות N2 עם 32 ליבות וירטואליות, ו-Intel Cascade Lake כפלטפורמת ה-CPU המינימלית. בנוסף, מוסבר איך ליצור מופע יחיד כדי להשתמש בהזמנה.

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

  1. כדי ליצור הזמנה לדוגמה, מבצעים את השלבים הבאים:

    1. פותחים את הדף Reservations במסוף Google Cloud .

      כניסה לדף Reservations

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

    2. בכרטיסייה מקום שמור על פי דרישה (ברירת המחדל), לוחצים על ‎ יצירת מקום שמור. ייפתח הדף Create a reservation.

    3. בשדה Name, מזינים שם להזמנה. לדוגמה, מזינים reservation-02.

    4. מציינים את האזור והתחום שבהם רוצים לשמור מקום למשאבים. בדוגמה הזו, בוחרים באפשרויות us-central1 ו-us-central1-a.

    5. בקטע Share type, מבצעים אחת מהפעולות הבאות:

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

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

    6. בקטע Use with VM instance, בוחרים באפשרות Select specific reservation.

    7. בשדה Number of VM instances (מספר מכונות ה-VM), מזינים את הערך 3.

    8. בכרטיסייה לשימוש כללי, בוחרים באפשרות N2.

    9. בקטע סוג מכונה, בכרטיסייה Preset (ברירת מחדל), בוחרים באפשרות n2-standard-32.

    10. מרחיבים את האפשרות CPU platform and GPU (פלטפורמת מעבד ו-GPU) ואז בשדה CPU platform (פלטפורמת מעבד) בוחרים באפשרות Intel Cascade Lake or later (פלטפורמת מעבד Intel Cascade Lake או גרסה מתקדמת יותר).

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

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

    1. נכנסים לדף Create an instance במסוף Google Cloud .

      כניסה לדף Create an instance

      הדף Create an instance מופיע ובו החלונית Machine configuration.

    2. בחלונית Machine configuration (הגדרת המכונה):

      1. בשדה Name, מזינים שם למופע. בדוגמה הזו, מזינים instance-02.

      2. מציינים את האזור והתחום שבהם רוצים לשמור מקום למשאבים. בדוגמה הזו, בוחרים באפשרויות us-central1 ו-us-central1-a.

      3. בכרטיסייה לשימוש כללי, בוחרים באפשרות N2.

      4. בקטע סוג מכונה, בכרטיסייה Preset (ברירת מחדל), בוחרים באפשרות n2-standard-32.

      5. מרחיבים את הקטע אפשרויות מתקדמות, ואז בשדה פלטפורמת CPU בוחרים באפשרות Intel Cascade Lake או גרסה מתקדמת יותר.

    3. בתפריט הניווט, לוחצים על מתקדם. מופיע החלונית מתקדם.

    4. בקטע Reservations (הזמנות), בוחרים באפשרות Choose a reservation (בחירת הזמנה) ואז לוחצים על Choose reservation (בחירת הזמנה).

    5. בחלונית Choose a reservation שמופיעה, מבצעים את הפעולות הבאות:

      1. בוחרים את ההזמנה הספציפית שיצרתם בשלבים הקודמים. אם רוצים להשתמש בהזמנה משותפת שקיימת בפרויקט אחר, בוחרים את הפרויקט שבו קיימת ההזמנה ברשימה Project.

      2. לוחצים על בחירה.

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

gcloud

בדוגמה הבאה מוצג איך ליצור הזמנה ספציפית באזור us-central1-a לשלוש מכונות N2 עם 32 ליבות וירטואליות, ו-Intel Cascade Lake כפלטפורמת ה-CPU המינימלית. בנוסף, מוסבר איך ליצור מופע יחיד כדי להשתמש בהזמנה.

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

  1. כדי ליצור את ההזמנה לדוגמה, משתמשים בפקודה gcloud compute reservations create עם הדגל --require-specific-reservation:

    gcloud compute reservations create reservation-02 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --require-specific-reservation \
        --vm-count=3 \
        --zone=us-central1-a
    
  2. כדי ליצור מכונה שצורכת את ההזמנה לדוגמה, משתמשים בפקודה gcloud compute instances create עם הדגלים --reservation ו---reservation-affinity=specific:

    gcloud compute instances create instance-02 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --reservation-affinity=specific \
        --reservation=RESERVATION_URL \
        --zone=us-central1-a
    

    מחליפים את RESERVATION_URL בכתובת ה-URL של ההזמנה. מציינים אחד מהערכים הבאים:

    • אם יצרתם את ההזמנה באותו פרויקט: reservation-02

    • אם ההזמנה היא בפרויקט אחר: projects/PROJECT_ID/reservations/reservation-02

המשך

בדוגמאות הבאות מוסבר איך ליצור מכונת N2 עם 32 מעבדי CPU וירטואליים, ועם Intel Cascade Lake כפלטפורמת ה-CPU המינימלית, באזור us-central1-a כדי להשתמש בהזמנה ספציפית שתואמת למכונה:

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

    import (
    	"context"
    	"fmt"
    	"io"
    
    	compute "cloud.google.com/go/compute/apiv1"
    	computepb "cloud.google.com/go/compute/apiv1/computepb"
    	"google.golang.org/protobuf/proto"
    )
    
    // consumeSpecificReservation creates instance, consuming specific reservation
    // Note: respective reservation should have SpecificReservationRequired: true
    func consumeSpecificReservation(w io.Writer, projectID, zone, instanceName, reservationName string) error {
    	// projectID := "your_project_id"
    	// zone := "us-west3-a"
    	// reservationName := "your_reservation_name"
    	// instanceName := "your_instance_name"
    
    	ctx := context.Background()
    	machineType := fmt.Sprintf("zones/%s/machineTypes/%s", zone, "n2-standard-32")
    	sourceImage := "projects/debian-cloud/global/images/family/debian-12"
    
    	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{
    			Disks: []*computepb.AttachedDisk{
    				{
    					InitializeParams: &computepb.AttachedDiskInitializeParams{
    						DiskSizeGb:  proto.Int64(10),
    						SourceImage: proto.String(sourceImage),
    					},
    					AutoDelete: proto.Bool(true),
    					Boot:       proto.Bool(true),
    					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
    				},
    			},
    			MachineType:    proto.String(machineType),
    			MinCpuPlatform: proto.String("Intel Cascade Lake"),
    			Name:           proto.String(instanceName),
    			NetworkInterfaces: []*computepb.NetworkInterface{
    				{
    					Name: proto.String("global/networks/default"),
    				},
    			},
    			// specifies particular reservation, which should be consumed
    			ReservationAffinity: &computepb.ReservationAffinity{
    				ConsumeReservationType: proto.String("SPECIFIC_RESERVATION"),
    				Key:                    proto.String("compute.googleapis.com/reservation-name"),
    				Values:                 []string{reservationName},
    			},
    		},
    	}
    
    	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 from reservation\n")
    
    	return nil
    }
    
  • כדי ליצור את מופע לדוגמה לשימוש בהזמנה ספציפית משותפת, משתמשים בדוגמת הקוד הבאה:

    import (
    	"context"
    	"fmt"
    	"io"
    
    	computepb "cloud.google.com/go/compute/apiv1/computepb"
    	"google.golang.org/protobuf/proto"
    )
    
    // consumeSpecificSharedReservation consumes specific shared reservation in particular zone
    func consumeSpecificSharedReservation(w io.Writer, client InstanceClientInterface, projectID, baseProjectId, zone, instanceName, reservationName string) error {
    	// client, err := compute.NewInstancesRESTClient(ctx)
    	// projectID := "your_project_id". Project where reservation is created.
    	// baseProjectId := "shared_project_id". Project where instance will be consumed and created.
    	// zone := "us-west3-a"
    	// reservationName := "your_reservation_name"
    	// instanceName := "your_instance_name"
    
    	ctx := context.Background()
    	machineType := fmt.Sprintf("zones/%s/machineTypes/%s", zone, "n2-standard-32")
    	sourceImage := "projects/debian-cloud/global/images/family/debian-12"
    	sharedReservation := fmt.Sprintf("projects/%s/reservations/%s", baseProjectId, reservationName)
    
    	req := &computepb.InsertInstanceRequest{
    		Project: projectID,
    		Zone:    zone,
    		InstanceResource: &computepb.Instance{
    			Disks: []*computepb.AttachedDisk{
    				{
    					InitializeParams: &computepb.AttachedDiskInitializeParams{
    						DiskSizeGb:  proto.Int64(10),
    						SourceImage: proto.String(sourceImage),
    					},
    					AutoDelete: proto.Bool(true),
    					Boot:       proto.Bool(true),
    					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
    				},
    			},
    			MachineType:    proto.String(machineType),
    			MinCpuPlatform: proto.String("Intel Cascade Lake"),
    			Name:           proto.String(instanceName),
    			NetworkInterfaces: []*computepb.NetworkInterface{
    				{
    					Name: proto.String("global/networks/default"),
    				},
    			},
    			// specifies particular reservation, which should be consumed
    			ReservationAffinity: &computepb.ReservationAffinity{
    				ConsumeReservationType: proto.String("SPECIFIC_RESERVATION"),
    				Key:                    proto.String("compute.googleapis.com/reservation-name"),
    				Values:                 []string{sharedReservation},
    			},
    		},
    	}
    
    	op, err := client.Insert(ctx, req)
    	if err != nil {
    		return fmt.Errorf("unable to create instance: %w", err)
    	}
    
    	if op != nil {
    		if err = op.Wait(ctx); err != nil {
    			return fmt.Errorf("unable to wait for the operation: %w", err)
    		}
    	}
    	fmt.Fprintf(w, "Instance created from shared reservation\n")
    
    	return nil
    }
    

Java

בדוגמאות הבאות מוסבר איך ליצור מכונת N1 עם ארבע ליבות וירטואליות (vCPU), ו-Intel Skylake כפלטפורמת ה-CPU המינימלית, באזור us-central1-a כדי להשתמש בהזמנה ספציפית שתואמת למכונה:

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

    import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.SPECIFIC_RESERVATION;
    
    import com.google.api.gax.longrunning.OperationFuture;
    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.InstancesClient;
    import com.google.cloud.compute.v1.NetworkInterface;
    import com.google.cloud.compute.v1.Operation;
    import com.google.cloud.compute.v1.ReservationAffinity;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class ConsumeSingleProjectReservation {
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(developer): Replace these variables before running the sample.
        // Project ID or project number of the Cloud project you want to use.
        String projectId = "YOUR_PROJECT_ID";
        // Name of the zone where the reservation is located.
        String zone = "us-central1-a";
        // Name of the reservation you want to query.
        String reservationName = "YOUR_RESERVATION_NAME";
        // Name of the VM instance you want to query.
        String instanceName = "YOUR_INSTANCE_NAME";
        // machineType: machine type of the VM being created.
        // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
        String machineTypeName = "n1-standard-4";
        // sourceImage: path to the operating system image to mount.
        // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
        String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
        // diskSizeGb: storage size of the boot disk to attach to the instance.
        long diskSizeGb = 10L;
        // networkName: network interface to associate with the instance.
        String networkName = "default";
        // Minimum CPU platform of the instances.
        String minCpuPlatform = "Intel Skylake";
    
        createInstanceAsync(projectId, zone, instanceName, reservationName, machineTypeName,
            sourceImage, diskSizeGb, networkName, minCpuPlatform);
      }
    
      // Create a virtual machine targeted with the reserveAffinity field.
      // Ensure that the VM's properties match the reservation's VM properties.
      public static Instance createInstanceAsync(String projectId, String zone, String instanceName,
          String reservationName, String machineTypeName, String sourceImage, long diskSizeGb,
          String networkName, String minCpuPlatform)
          throws IOException, InterruptedException, ExecutionException, TimeoutException {
        String machineType = String.format("zones/%s/machineTypes/%s", zone, machineTypeName);
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (InstancesClient instancesClient = InstancesClient.create()) {
          AttachedDisk disk =
              AttachedDisk.newBuilder()
                  .setBoot(true)
                  .setAutoDelete(true)
                  .setType(AttachedDisk.Type.PERSISTENT.toString())
                  .setDeviceName("disk-1")
                  .setInitializeParams(
                      AttachedDiskInitializeParams.newBuilder()
                          .setSourceImage(sourceImage)
                          .setDiskSizeGb(diskSizeGb)
                          .build())
                  .build();
    
          NetworkInterface networkInterface = NetworkInterface.newBuilder()
              .setName(networkName)
              .build();
    
          ReservationAffinity reservationAffinity =
              ReservationAffinity.newBuilder()
                  .setConsumeReservationType(SPECIFIC_RESERVATION.toString())
                  .setKey("compute.googleapis.com/reservation-name")
                  // Set specific reservation
                  .addValues(reservationName)
                  .build();
    
          Instance instanceResource =
              Instance.newBuilder()
                  .setName(instanceName)
                  .setMachineType(machineType)
                  .addDisks(disk)
                  .addNetworkInterfaces(networkInterface)
                  .setMinCpuPlatform(minCpuPlatform)
                  .setReservationAffinity(reservationAffinity)
                  .build();
    
          InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
              .setProject(projectId)
              .setZone(zone)
              .setInstanceResource(instanceResource)
              .build();
    
          OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
              insertInstanceRequest);
          Operation response = operation.get(3, TimeUnit.MINUTES);
    
          if (response.hasError()) {
            return null;
          }
          return instancesClient.get(projectId, zone, instanceName);
        }
      }
    }
  • כדי ליצור הזמנה לדוגמה כהזמנה משותפת וליצור מכונה שתשתמש בה, אפשר להשתמש בדוגמת הקוד הבאה:

    import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.SPECIFIC_RESERVATION;
    
    import com.google.api.gax.longrunning.OperationFuture;
    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.InstancesClient;
    import com.google.cloud.compute.v1.NetworkInterface;
    import com.google.cloud.compute.v1.Operation;
    import com.google.cloud.compute.v1.ReservationAffinity;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class ConsumeSpecificSharedReservation {
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(developer): Replace these variables before running the sample.
        // Project ID or project number of the Cloud project you want to use.
        String projectId = "YOUR_PROJECT_ID";
        // Name of the zone the reservation is located.
        String zone = "us-central1-a";
        // Name of the reservation you want to query.
        String reservationName = "YOUR_RESERVATION_NAME";
        // Name of the VM instance you want to query.
        String instanceName = "YOUR_INSTANCE_NAME";
        // machineType: machine type of the VM being created.
        // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
        String machineTypeName = "n1-standard-4";
        // sourceImage: path to the operating system image to mount.
        // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
        String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
        // diskSizeGb: storage size of the boot disk to attach to the instance.
        long diskSizeGb = 10L;
        // networkName: network interface to associate with the instance.
        String networkName = "default";
        // Minimum CPU platform of the instances.
        String minCpuPlatform = "Intel Skylake";
    
        createInstanceAsync(projectId, zone, instanceName, reservationName, machineTypeName,
            sourceImage, diskSizeGb, networkName, minCpuPlatform);
      }
    
      // Create a virtual machine targeted with the reserveAffinity field.
      // Ensure that the VM's properties match the reservation's VM properties.
      public static Instance createInstanceAsync(String projectId, String zone, String instanceName,
          String reservationName, String machineTypeName, String sourceImage, long diskSizeGb,
          String networkName, String minCpuPlatform)
          throws IOException, InterruptedException, ExecutionException, TimeoutException {
        String machineType = String.format("zones/%s/machineTypes/%s", zone, machineTypeName);
        // To consume this reservation from any consumer projects that this reservation is shared with,
        // you must also specify the owner project of the reservation - the path to the reservation.
        String reservationPath =
            String.format("projects/%s/reservations/%s", projectId, reservationName);
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (InstancesClient instancesClient = InstancesClient.create()) {
          AttachedDisk disk =
              AttachedDisk.newBuilder()
                  .setBoot(true)
                  .setAutoDelete(true)
                  .setType(AttachedDisk.Type.PERSISTENT.toString())
                  .setDeviceName("disk-1")
                  .setInitializeParams(
                      AttachedDiskInitializeParams.newBuilder()
                          .setSourceImage(sourceImage)
                          .setDiskSizeGb(diskSizeGb)
                          .build())
                  .build();
    
          NetworkInterface networkInterface = NetworkInterface.newBuilder()
              .setName(networkName)
              .build();
    
          ReservationAffinity reservationAffinity =
              ReservationAffinity.newBuilder()
                  .setConsumeReservationType(SPECIFIC_RESERVATION.toString())
                  .setKey("compute.googleapis.com/reservation-name")
                  // Set specific reservation
                  .addValues(reservationPath)
                  .build();
    
          Instance instanceResource =
              Instance.newBuilder()
                  .setName(instanceName)
                  .setMachineType(machineType)
                  .addDisks(disk)
                  .addNetworkInterfaces(networkInterface)
                  .setMinCpuPlatform(minCpuPlatform)
                  .setReservationAffinity(reservationAffinity)
                  .build();
    
          InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
              .setProject(projectId)
              .setZone(zone)
              .setInstanceResource(instanceResource)
              .build();
    
          OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
              insertInstanceRequest);
          Operation response = operation.get(3, TimeUnit.MINUTES);
    
          if (response.hasError()) {
            return null;
          }
          return instancesClient.get(projectId, zone, instanceName);
        }
      }
    }

Node.js

בדוגמאות הבאות מוסבר איך ליצור מכונת N1 עם 4 מעבדי CPU וירטואליים, ו-Intel Skylake כפלטפורמת ה-CPU המינימלית, באזור us-central1-a כדי להשתמש בהזמנה ספציפית שתואמת למכונה:

// Import the Compute library
const computeLib = require('@google-cloud/compute');
const compute = computeLib.protos.google.cloud.compute.v1;

// Instantiate a reservationsClient
const instancesClient = new computeLib.InstancesClient();
// Instantiate a zoneOperationsClient
const zoneOperationsClient = new computeLib.ZoneOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The ID of the project where you want to create instance.
const projectId = await instancesClient.getProjectId();
// The zone in which to create instance.
const zone = 'us-central1-a';
// The name of the instance to create.
// const instanceName = 'instance-01';
// The name of the reservation to consume.
// Ensure that the specificReservationRequired field in reservation properties is set to true.
// const reservationName = 'reservation-01';
// Machine type to use for VM.
const machineType = 'n1-standard-4';

// Create instance to consume a specific single-project reservation
async function callCreateInstanceToConsumeSingleProjectReservation() {
  // Describe the size and source image of the boot disk to attach to the instance.
  // Ensure that the VM's properties match the reservation's VM properties,
  // including the zone, machine type (machine family, vCPUs, and memory),
  // minimum CPU platform, GPU amount and type, and local SSD interface and size
  const disk = new compute.Disk({
    boot: true,
    autoDelete: true,
    type: 'PERSISTENT',
    initializeParams: {
      diskSizeGb: '10',
      sourceImage: 'projects/debian-cloud/global/images/family/debian-12',
    },
  });

  //  Define networkInterface
  const networkInterface = new compute.NetworkInterface({
    name: 'global/networks/default',
  });

  // Define reservationAffinity
  const reservationAffinity = new compute.ReservationAffinity({
    consumeReservationType: 'SPECIFIC_RESERVATION',
    key: 'compute.googleapis.com/reservation-name',
    values: [reservationName],
  });

  // Create an instance
  const instance = new compute.Instance({
    name: instanceName,
    machineType: `zones/${zone}/machineTypes/${machineType}`,
    minCpuPlatform: 'Intel Skylake',
    disks: [disk],
    networkInterfaces: [networkInterface],
    reservationAffinity,
  });

  const [response] = await instancesClient.insert({
    project: projectId,
    instanceResource: instance,
    zone,
  });

  let operation = response.latestResponse;

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

  console.log(`Instance ${instanceName} created.`);
}

await callCreateInstanceToConsumeSingleProjectReservation();

Python

בדוגמאות הבאות מוסבר איך ליצור מכונת N2 עם 32 מעבדי CPU וירטואליים, ועם Intel Cascade Lake כפלטפורמת ה-CPU המינימלית, באזור us-central1-a כדי להשתמש בהזמנה ספציפית שתואמת למכונה:

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

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

    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 consume_specific_single_project_reservation(
        project_id: str,
        zone: str,
        reservation_name: str,
        instance_name: str,
        machine_type: str = "n1-standard-1",
        min_cpu_platform: str = "Intel Ivy Bridge",
    ) -> compute_v1.Instance:
        """
        Creates a specific reservation in a single project and launches a VM
        that consumes the newly created reservation.
        Args:
            project_id (str): The ID of the Google Cloud project.
            zone (str): The zone to create the reservation.
            reservation_name (str): The name of the reservation to create.
            instance_name (str): The name of the instance to create.
            machine_type (str): The machine type for the instance.
            min_cpu_platform (str): The minimum CPU platform for the instance.
        """
        instance_properties = (
            compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
                machine_type=machine_type,
                min_cpu_platform=min_cpu_platform,
            )
        )
    
        reservation = compute_v1.Reservation(
            name=reservation_name,
            specific_reservation=compute_v1.AllocationSpecificSKUReservation(
                count=3,
                instance_properties=instance_properties,
            ),
            # Only VMs that target the reservation by name can consume from this reservation
            specific_reservation_required=True,
        )
    
        # Create a reservation client
        client = compute_v1.ReservationsClient()
        operation = client.insert(
            project=project_id,
            zone=zone,
            reservation_resource=reservation,
        )
        wait_for_extended_operation(operation, "Reservation creation")
    
        instance = compute_v1.Instance()
        instance.name = instance_name
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
        instance.min_cpu_platform = min_cpu_platform
        instance.zone = zone
    
        # Set the reservation affinity to target the specific reservation
        instance.reservation_affinity = compute_v1.ReservationAffinity(
            consume_reservation_type="SPECIFIC_RESERVATION",  # Type of reservation to consume
            key="compute.googleapis.com/reservation-name",  # Key for the reservation
            values=[reservation_name],  # Reservation name to consume
        )
        # Define the disks for the instance
        instance.disks = [
            compute_v1.AttachedDisk(
                boot=True,  # Indicates that this is a boot disk
                auto_delete=True,  # The disk will be deleted when the instance is deleted
                initialize_params=compute_v1.AttachedDiskInitializeParams(
                    source_image="projects/debian-cloud/global/images/family/debian-11",
                    disk_size_gb=10,
                ),
            )
        ]
        instance.network_interfaces = [
            compute_v1.NetworkInterface(
                network="global/networks/default",  # The network to use
                access_configs=[
                    compute_v1.AccessConfig(
                        name="External NAT",  # Name of the access configuration
                        type="ONE_TO_ONE_NAT",  # Type of access configuration
                    )
                ],
            )
        ]
        # Create a request to insert the instance
        request = compute_v1.InsertInstanceRequest()
        request.zone = zone
        request.project = project_id
        request.instance_resource = instance
    
        vm_client = compute_v1.InstancesClient()
        operation = vm_client.insert(request)
        wait_for_extended_operation(operation, "instance creation")
        print(f"Instance {instance_name} with specific reservation created successfully.")
    
        return vm_client.get(project=project_id, zone=zone, instance=instance_name)
    
    
  • כדי ליצור את ההזמנה לדוגמה ולהשתמש בה כהזמנה משותפת, אפשר להשתמש בדוגמת הקוד הבאה:

    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 consume_specific_shared_project_reservation(
        owner_project_id: str,
        shared_project_id: str,
        zone: str,
        reservation_name: str,
        instance_name: str,
        machine_type: str = "n1-standard-1",
        min_cpu_platform: str = "Intel Ivy Bridge",
    ) -> compute_v1.Instance:
        """
        Creates a specific reservation in a single project and launches a VM
        that consumes the newly created reservation.
        Args:
            owner_project_id (str): The ID of the Google Cloud project.
            shared_project_id: The ID of the owner project of the reservation in the same zone.
            zone (str): The zone to create the reservation.
            reservation_name (str): The name of the reservation to create.
            instance_name (str): The name of the instance to create.
            machine_type (str): The machine type for the instance.
            min_cpu_platform (str): The minimum CPU platform for the instance.
        """
        instance_properties = (
            compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
                machine_type=machine_type,
                min_cpu_platform=min_cpu_platform,
            )
        )
    
        reservation = compute_v1.Reservation(
            name=reservation_name,
            specific_reservation=compute_v1.AllocationSpecificSKUReservation(
                count=3,
                instance_properties=instance_properties,
            ),
            # Only VMs that target the reservation by name can consume from this reservation
            specific_reservation_required=True,
            share_settings=compute_v1.ShareSettings(
                share_type="SPECIFIC_PROJECTS",
                project_map={
                    shared_project_id: compute_v1.ShareSettingsProjectConfig(
                        project_id=shared_project_id
                    )
                },
            ),
        )
    
        # Create a reservation client
        client = compute_v1.ReservationsClient()
        operation = client.insert(
            project=owner_project_id,
            zone=zone,
            reservation_resource=reservation,
        )
        wait_for_extended_operation(operation, "Reservation creation")
    
        instance = compute_v1.Instance()
        instance.name = instance_name
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
        instance.min_cpu_platform = min_cpu_platform
        instance.zone = zone
    
        # Set the reservation affinity to target the specific reservation
        instance.reservation_affinity = compute_v1.ReservationAffinity(
            consume_reservation_type="SPECIFIC_RESERVATION",  # Type of reservation to consume
            key="compute.googleapis.com/reservation-name",
            # To consume this reservation from any consumer projects, specify the owner project of the reservation
            values=[f"projects/{owner_project_id}/reservations/{reservation_name}"],
        )
        # Define the disks for the instance
        instance.disks = [
            compute_v1.AttachedDisk(
                boot=True,  # Indicates that this is a boot disk
                auto_delete=True,  # The disk will be deleted when the instance is deleted
                initialize_params=compute_v1.AttachedDiskInitializeParams(
                    source_image="projects/debian-cloud/global/images/family/debian-11",
                    disk_size_gb=10,
                ),
            )
        ]
        instance.network_interfaces = [
            compute_v1.NetworkInterface(
                network="global/networks/default",  # The network to use
                access_configs=[
                    compute_v1.AccessConfig(
                        name="External NAT",  # Name of the access configuration
                        type="ONE_TO_ONE_NAT",  # Type of access configuration
                    )
                ],
            )
        ]
        # Create a request to insert the instance
        request = compute_v1.InsertInstanceRequest()
        request.zone = zone
        # The instance will be created in the shared project
        request.project = shared_project_id
        request.instance_resource = instance
    
        vm_client = compute_v1.InstancesClient()
        operation = vm_client.insert(request)
        wait_for_extended_operation(operation, "instance creation")
        print(f"Instance {instance_name} from project {owner_project_id} created.")
        # The instance is created in the shared project, so we return it from there.
        return vm_client.get(project=shared_project_id, zone=zone, instance=instance_name)
    
    

REST

בדוגמה הבאה מוצג איך ליצור הזמנה ספציפית באזור us-central1-a לשלוש מכונות N2 עם 32 ליבות וירטואליות, ו-Intel Cascade Lake כפלטפורמת ה-CPU המינימלית. בנוסף, מוסבר איך ליצור מופע יחיד כדי להשתמש בהזמנה.

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

  1. כדי ליצור את הבקשה לדוגמה לשמירת מקום, שולחים בקשת POST אל ה-method‏ instances.insert. בגוף הבקשה, כוללים את השדה specificReservationRequired עם הערך true:

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations
    
    {
      "name": "reservation-02",
      "specificReservation": {
        "count": "3",
        "instanceProperties": {
          "machineType": "n2-standard-32",
          "minCpuPlatform": "Intel Cascade Lake",
        }
      },
      "specificReservationRequired": true
    }
    
  2. כדי ליצור מכונה שצורכת את ההזמנה לדוגמה, שולחים בקשת POST אל ה-method‏ instances.insert. בגוף הבקשה, בשדה reservationAffinity, כוללים את הפרטים הבאים:

    • השדה consumeReservationType מוגדר ל-SPECIFIC_RESERVATION.

    • השדה key מוגדר ל-compute.googleapis.com/reservation-name.

    • השדה values מוגדר לכתובת ה-URL של ההזמנה.

    הבקשה תיראה כך:

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/instances
    
    {
      "name": "instance-02",
      "machineType": "zones/us-central1-a/machineTypes/n2-standard-32",
      "minCpuPlatform": "Intel Cascade Lake",
      "disks": [
        {
          "boot": true,
          "initializeParams": {
            "sourceImage": "projects/debian-cloud/global/images/family/debian-12"
          }
        }
      ],
      "networkInterfaces": [
        {
          "network": "global/networks/default"
        }
      ],
      "reservationAffinity": {
        "consumeReservationType": "SPECIFIC_RESERVATION",
        "key": "compute.googleapis.com/reservation-name",
        "values": [
          "RESERVATION_URL"
        ]
      }
    }
    

    מחליפים את RESERVATION_URL בכתובת ה-URL של ההזמנה. מציינים אחד מהערכים הבאים:

    • אם יצרתם את ההזמנה באותו פרויקט: reservation-02

    • אם ההזמנה היא בפרויקט אחר: projects/PROJECT_ID/reservations/reservation-02

שימוש במקום שמור שנוצר אוטומטית לבקשה במצב יומן

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

כדי להשתמש בסוג כזה של הזמנה, צריך ליצור מופע באופן הבא:

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

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

המסוף

  1. יוצרים בקשה לדוגמה לחמש מכונות A3 Ultra ושולחים אותה לבדיקה:

    1. פותחים את הדף Reservations במסוף Google Cloud .

      כניסה לדף Reservations

    2. לוחצים על הכרטיסייה Future reservations.

    3. לוחצים על ‎ Create future reservation‎. ייפתח הדף Create a future reservation.

    4. לוחצים על הכרטיסייה GPUs ואז ברשימה GPU type בוחרים באפשרות NVIDIA H200 141GB. הפעולה הזו מציינת מופע A3 Ultra.

    5. בשדה Total capacity needed, מזינים 5.

    6. בקטע Reservation period, מציינים את שעת ההתחלה ואת משך הזמן של תקופת שמירת המקום.

    7. לוחצים על חיפוש קיבולת ואז בקטע קיבולת זמינה בוחרים אחת מהמכונות הזמינות.

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

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

    1. נכנסים לדף Create an instance במסוף Google Cloud .

      כניסה לדף Create an instance

    2. בשדה Name, מזינים שם למופע. בדוגמה הזו, מזינים example-instance.

    3. מציינים את האזור והתחום שבהם נמצאת ההזמנה שנוצרה אוטומטית. לצורך הדוגמה הזו, בוחרים באפשרויות us-central1 ו-us-central1-b.

    4. לוחצים על הכרטיסייה GPUs ואז ברשימה GPU type בוחרים באפשרות NVIDIA H200 141GB. הפעולה הזו מציינת מופע A3 Ultra ומגדירה את מודל ההקצאה לReservation-bound.

    5. בתפריט הניווט, לוחצים על מתקדם.

    6. בקטע Reservations, בוחרים באפשרות Choose a reservation ואז לוחצים על Choose a reservation.

    7. בחלונית Choose a reservation:

      1. בוחרים את ההזמנה לדוגמה שנוצרה אוטומטית.

      2. לוחצים על בחירה.

    8. בקטע Provisioning model, מרחיבים את הקטע VM provisioning model advanced settings.

    9. ברשימה On VM termination בוחרים באפשרות Stop (ברירת מחדל) או באפשרות Delete.

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

gcloud

  1. כדי ליצור בקשה לדוגמה לחמש מכונות וירטואליות מסוג A3 Ultra ולשלוח אותה לבדיקה, משתמשים בפקודה gcloud compute future-reservations create:

    gcloud compute future-reservations create example-fr \
        --auto-delete-auto-created-reservations \
        --deployment-type=DENSE \
        --planning-status=SUBMITTED \
        --require-specific-reservation \
        --reservation-mode=CALENDAR \
        --reservation-name=example-reservation \
        --share-setting=local \
        --start-time=2026-03-05T00:00:00Z \
        --end-time=2026-03-19T00:00:00Z \
        --machine-type=a3-ultragpu-8g \
        --total-count=5 \
        --zone=us-central1-b
    

    נניח ש Google Cloud מאשר את הבקשה ו-Compute Engine יוצר באופן אוטומטי שמירת מקום ריקה. בזמן תחילת הבקשה, ב-5 במרץ 2026,‏ Compute Engine מגדיל את מספר המכונות הווירטואליות עם GPU שמוזמנות במקום השמור. אחר כך תוכלו להשתמש בהזמנה.

  2. כדי ליצור מכונת A3 Ultra שתשתמש בהזמנה לדוגמה שנוצרה אוטומטית, משתמשים בפקודה gcloud compute instances create עם הדגלים הבאים:

    • הדגל של --instance-termination-action.

    • הדגל --provisioning-model מוגדר לערך RESERVATION_BOUND.

    • הדגל של --reservation.

    • הדגל --reservation-affinity מוגדר לערך specific.

    הפקודה דומה לפקודה הבאה. הדרישות המלאות ליצירת מכונת A3 Ultra מפורטות במאמר יצירת מכונת A3 Ultra או A4.

    gcloud compute instance create example-a3ultra-instance  \
        --machine-type=a3-ultragpu-8g \
        --instance-termination-action=TERMINATION_ACTION \
        --provisioning-model=RESERVATION_BOUND \
        --reservation-affinity=specific \
        --reservation=RESERVATION_URL \
        --zone=us-central1-b \
        ...
    

    הפקודה כוללת את הערכים הבאים:

    • TERMINATION_ACTION: האם Compute Engine מפסיק (STOP) או מוחק (DELETE) את המכונה הווירטואלית בסוף תקופת השמירה.

    • RESERVATION_URL: כתובת ה-URL של ההזמנה, בפורמט הבא:

      • אם ההזמנה שנוצרה אוטומטית קיימת בפרויקט: example-reservation.

      • אם ההזמנה שנוצרה אוטומטית קיימת בפרויקט אחר: projects/PROJECT_ID/reservations/example-reservation.

REST

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

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-b/futureReservations
    
    {
      "name": "example-request-calendar-mode",
      "autoDeleteAutoCreatedReservations": true,
      "deploymentType": "DENSE",
      "planningStatus": "SUBMITTED",
      "reservationMode": "CALENDAR",
      "reservationName": "example-reservation",
      "shareSettings": {
        "shareType": "LOCAL"
      },
      "specificReservationRequired": true,
      "specificSkuProperties": {
        "machineType": "a3-ultragpu-8g",
        "totalCount": 5
      },
      "timeWindow": {
        "startTime": "2026-03-05T00:00:00Z",
        "endTime": "2026-03-19T00:00:00Z"
      }
    }
    

    נניח ש Google Cloud מאשר את הבקשה ו-Compute Engine יוצר באופן אוטומטי שמירת מקום ריקה. בשעת ההתחלה של הבקשה, ב-5 במרץ 2026, מערכת Compute Engine מגדילה את מספר המכונות הווירטואליות (VM) עם GPU ששמורות במקום השמור. אחר כך תוכלו להשתמש בהזמנה.

  2. בשעת ההתחלה של הבקשה, כדי ליצור מכונת A3 Ultra שתשתמש בהזמנה לדוגמה שנוצרה אוטומטית, שולחים בקשת POST אל ה-method‏ instances.insert. בגוף הבקשה, כוללים את השדות הבאים:

    • השדה reservationAffinity.consumeReservationType מוגדר ל-SPECIFIC_RESERVATION.

    • השדה reservationAffinity.key מוגדר ל-compute.googleapis.com/reservation-name.

    • השדה reservationAffinity.values מוגדר לכתובת ה-URL של ההזמנה.

    • השדה scheduling.instanceTerminationAction.

    • השדה scheduling.provisioningModel מוגדר ל-RESERVATION_BOUND.

    הבקשה תיראה כך: הדרישות המלאות ליצירת מכונת A3 Ultra מפורטות במאמר יצירת מכונת A3 Ultra או A4.

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-b/
    
    {
      {
        "machineType": "projects/example-project/zones/us-central1-b/machineTypes/a3-ultragpu-8g",
        "name": "example-a3ultra-instance",
        "reservationAffinity": {
          "consumeReservationType": "SPECIFIC_RESERVATION",
          "key": "compute.googleapis.com/reservation-name",
          "values":[
            "RESERVATION_URL"
          ],
        },
        "scheduling": {
          "instanceTerminationAction": "TERMINATION_ACTION",
          "provisioningModel": "RESERVATION_BOUND"
        },
        ...
      }
    }
    

    גוף הבקשה כולל את הערכים הבאים:

    • RESERVATION_URL: כתובת ה-URL של ההזמנה, בפורמט הבא:

      • אם ההזמנה שנוצרה אוטומטית קיימת בפרויקט: example-reservation.

      • אם ההזמנה שנוצרה אוטומטית קיימת בפרויקט אחר: projects/PROJECT_ID/reservations/example-reservation.

    • TERMINATION_ACTION: האם Compute Engine מפסיק (STOP) או מוחק (DELETE) את המכונה הווירטואלית בסוף תקופת השמירה.

בדיקה שמאפייני המכונה תואמים להזמנה שנעשה בה שימוש באופן אוטומטי

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

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

  2. יוצרים מכונה לבדיקה כדי לצרוך את ההזמנה.

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

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

אימות השימוש בהזמנות

כדי לאמת את השימוש בהזמנות, אפשר להשתמש באחת מהשיטות הבאות:

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