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

במאמר הזה מוסבר איך להשתמש במקומות שמורים ב- Compute Engine.

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

מגבלות

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

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

  • VM במודל 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 מעבדי vCPU, ו-Intel Cascade Lake כפלטפורמת ה-CPU המינימלית. בנוסף, מוסבר איך ליצור מכונה אחת כדי להשתמש בהזמנה.

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

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

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

      כניסה לדף Reservations

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

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

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

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

    5. בקטע סוג השיתוף, מבצעים אחת מהפעולות הבאות:

      • כדי ליצור מקום שמור לפרויקט יחיד, בוחרים באפשרות 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 במסוף Cloud de Confiance .

      כניסה לדף 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 מעבדי vCPU, ו-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 עם ארבעה מעבדי 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 עם ארבעה מעבדי vCPU, ו-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

בדוגמה הבאה מוסבר איך ליצור הזמנה אוטומטית באזור 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 מעבדי vCPU, ו-Intel Cascade Lake כפלטפורמת ה-CPU המינימלית. בנוסף, מוסבר איך ליצור מכונה אחת כדי לצרוך את ההזמנה.

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

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

    POST https://compute.s3nsapis.fr/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.s3nsapis.fr/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"
      }
    }
    

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

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

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

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

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

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

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

      כניסה לדף Reservations

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

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

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

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

    5. בקטע סוג השיתוף, מבצעים אחת מהפעולות הבאות:

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

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

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

    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 במסוף Cloud de Confiance .

      כניסה לדף 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. מרחיבים את הקטע Advanced options, ובשדה CPU platform בוחרים באפשרות Intel Cascade Lake or later.

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

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

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

  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 מעבדי vCPU ופלטפורמת CPU מינימלית מסוג Intel Cascade Lake באזור 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{
    				{
    					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 עם ארבעה מעבדי vCPU ופלטפורמת CPU מינימלית מסוג Intel Skylake באזור 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);
        }
      }
    }
  • כדי ליצור הקצאה לדוגמה כהקצאה משותפת, וליצור מכונה שתשתמש בה, משתמשים בדוגמת הקוד הבאה:

    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 ופלטפורמת CPU מינימלית מסוג Intel Cascade Lake באזור 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

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

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

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

    POST https://compute.s3nsapis.fr/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.s3nsapis.fr/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.s3nsapis.fr/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 במסוף Cloud de Confiance .

      כניסה לדף Reservations

    2. לוחצים על הכרטיסייה מקום שמור לעתיד.

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

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

    5. בשדה Total capacity needed, כותבים 5.

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

    7. לוחצים על Search for capacity, ובקטע Available capacity בוחרים אחת מהמכונות הזמינות.

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

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

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

      כניסה לדף Create an instance

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

    3. מציינים את האזור (Region) ואת התחום (Zone) שבהם נמצאת ההזמנה שנוצרה באופן אוטומטי. בדוגמה הזו, בוחרים באפשרויות 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
    

    נניח ש- Cloud de Confiance מאשר את הבקשה ו-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 instances 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: אם המכונה הווירטואלית תופסק (STOP) או תימחק (DELETE) ב-Compute Engine בסוף תקופת ההזמנה.

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

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

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

REST

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

    POST https://compute.s3nsapis.fr/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": {
        "instanceProperties": {
          "machineType": "a3-ultragpu-8g"
        },
        "totalCount": "5"
      },
      "timeWindow": {
        "startTime": "2026-03-05T00:00:00Z",
        "endTime": "2026-03-19T00:00:00Z"
      }
    }
    

    נניח ש- Cloud de Confiance מאשר את הבקשה ו-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.s3nsapis.fr/compute/v1/projects/example-project/zones/us-central1-b/instances
    
    {
      "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: אם המכונה הווירטואלית תופסק (STOP) או תימחק (DELETE) ב-Compute Engine בסוף תקופת ההזמנה.

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

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

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

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

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

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

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

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

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

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

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