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

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

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

מגבלות

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

  • מכונות וירטואליות מסוג Flex-start

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

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

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

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

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

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

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

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

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

  • כדי ליצור הזמנות: ‫compute.reservations.create בפרויקט
  • כדי ליצור מכונות Compute:
    • ‫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. אפשר גם להשתמש בשמירת מקום על ידי יצירת מופעי מחשוב שתואמים למאפיינים של שמירת המקום באמצעות אפשרות פריסה אחרת, או על ידי עדכון המאפיינים של מופעי מחשוב קיימים כך שיתאימו לשמירת המקום שנעשה בה שימוש באופן אוטומטי.

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

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

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

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

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

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

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

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

המסוף

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

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

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

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

      כניסה לדף Reservations

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

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

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

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

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

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

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

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

    7. בשדה Number of VM instances, מזינים 3.

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

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

    10. מרחיבים את CPU platform and GPU, ובשדה CPU platform בוחרים באפשרות Intel Cascade Lake or later.

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

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

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

      כניסה לדף Create an instance

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

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

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

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

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

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

      5. מרחיבים את הקטע Advanced options ובשדה CPU platform בוחרים באפשרות Intel Cascade Lake or later.

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

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

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

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

gcloud

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

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

  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. כדי ליצור מכונת Compute שמשתמשת בהזמנה לדוגמה, משתמשים בפקודה 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 עם ארבעה מעבדי vCPU, ו-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-13";
    // 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-13",
                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"
      }
    }
    

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

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

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

שיטת יצירה כשיוצרים הזמנה כשיוצרים מכונות וירטואליות כדי לצרוך את ההזמנה
מסוף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.

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

המסוף

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

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

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

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

      כניסה לדף Reservations

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

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

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

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

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

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

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

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

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

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

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

    10. מרחיבים את CPU platform and GPU, ובשדה CPU platform בוחרים באפשרות Intel Cascade Lake or later.

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

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

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

      כניסה לדף Create an instance

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

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

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

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

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

      4. בקטע Machine type, בכרטיסייה 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 מעבדי vCPU, ו-Intel Cascade Lake כפלטפורמת ה-CPU המינימלית. בנוסף, מוסבר איך ליצור מכונה אחת של Compute Engine כדי להשתמש במקום שהוזמן.

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

  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. כדי ליצור מכונה של Compute Engine שמשתמשת בהזמנה לדוגמה, משתמשים בפקודה 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 כדי להשתמש בהזמנה ספציפית שתואמת למכונה:

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

    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{
    				{
    					Network: 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{
    				{
    					Network: 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 עם ארבעה מעבדי CPU וירטואליים, ו-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-13";
        // 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);
        }
      }
    }
  • כדי ליצור הקצאה לדוגמה כהקצאה משותפת, וליצור מכונה של Compute Engine שתשתמש בה, אפשר להשתמש בדוגמת הקוד הבאה:

    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-13";
        // 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 מעבדי vCPU ופלטפורמת CPU מינימלית מסוג Intel Skylake באזור 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 מעבדי vCPU ו-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-13",
                    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-13",
                    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

בדוגמה הבאה מוסבר איך ליצור מקום שמור ספציפי בתחום (zone) us-central1-a לשלוש מכונות N2 עם 32 vCPU, ו-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. כדי ליצור מכונה של Compute Engine שצורכת את המקום ששוריין בדוגמה, שולחים בקשת 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 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 מגדיל את מספר המכונות הווירטואליות השמורות עם 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) בסוף תקופת שמירת המקום.

בדיקה אם מאפייני מופע Compute תואמים למקום שמור שנצרך באופן אוטומטי

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

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

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

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

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

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

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

אימות צריכת ההזמנות

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

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