יצירת הזמנה לפרויקט יחיד

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

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

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

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

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

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

כדי לקבל את ההרשאות שנדרשות ליצירת הזמנות לפרויקט יחיד, צריך לבקש מהאדמין להקצות לכם ב-IAM את התפקיד אדמין של Compute (roles/compute.admin) בפרויקט. כדי לקרוא הסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

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

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

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

  • compute.reservations.create בפרויקט
  • כדי לציין תבנית של הגדרות מכונה: compute.instanceTemplates.useReadOnly בתבנית של הגדרות המכונה

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

שליחת בקשה לשריון מקום שמור לפרויקט מסוים

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

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

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

  • ציון של מכונה וירטואלית קיימת

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

  • ציון מאפיינים ישירות

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

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

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

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

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

  • יוצרים את המקום השמור באותו אזור ותחום (zone) שבו נמצאים המשאבים בתבנית של הגדרות מכונה. כל משאב אזורי או משאב של תחום מוגדר שמוגדר בתבנית של הגדרות מכונה – כמו סוג מכונה או נפח של דיסק אחסון מתמיד – מגביל את השימוש בתבנית למיקומים שבהם המשאבים האלה קיימים. לדוגמה, אם בתבנית של הגדרות המכונה מצוין נפח של דיסק אחסון מתמיד קיים באזור us-central1-a, אפשר ליצור את השריין רק באותו אזור. כדי לבדוק אם תבנית קיימת מציינת משאבים שמקשרים את התבנית לאזור או לאזור זמינות ספציפיים, צופים בפרטים של תבנית הגדרות המכונה ומחפשים בתוכה הפניות למשאבים אזוריים או למשאבים של אזור זמינות.

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

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

המסוף

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

    כניסה לדף Reservations

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

  3. נותנים לבקשה שם בשדה Name.

  4. ברשימות Region ו-Zone, בוחרים את האזור והתחום שבהם רוצים לשריין את המשאבים.

  5. אופציונלי: כדי לאפשר למשימות אימון בהתאמה אישית או למשימות חיזוי ב-Vertex AI להשתמש במכונות וירטואליות של GPU ששמורות במכסת השימוש, בקטע Google Cloud services בוחרים באפשרות Share reservation.

  6. בקטע Use with VM instance (שימוש עם מכונת VM), בוחרים באחת מהאפשרויות הבאות:

    • כדי להשתמש אוטומטית במכונות וירטואליות שמתאימות לפרטי הבקשה, מסמנים את האפשרות Use reservation automatically.

    • כדי להשתמש במשאבים שמתאימים לפרטי הבקשה רק כשיוצרים מכונות וירטואליות שמיועדות ספציפית אליה (לפי שם), בוחרים באפשרות Select specific reservation.

  7. בקטע Resource details (פרטי המשאב), מבצעים את הפעולות הבאות:

    • בשדה Number of VM instances מקלידים את מספר המכונות הווירטואליות שרוצים לשריין.

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

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

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

gcloud

כדי ליצור הזמנה לפרויקט יחיד, משתמשים בפקודה gcloud compute reservations create.

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

gcloud compute reservations create RESERVATION_NAME \
    --source-instance-template=INSTANCE_TEMPLATE_URL \
    --vm-count=NUMBER_OF_VMS \
    --zone=ZONE

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

  • RESERVATION_NAME: השם של ההזמנה שרוצים ליצור.

  • INSTANCE_TEMPLATE_URL: כתובת ה-URL של תבנית קיימת של הגדרות מכונה. מציינים אחד מהערכים הבאים:

    • לתבנית של הגדרות מכונה אזורית: projects/PROJECT_ID/regions/REGION/instanceTemplates/INSTANCE_TEMPLATE_NAME

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

  • NUMBER_OF_VMS: מספר המכונות הווירטואליות שרוצים לשריין.

  • ZONE: האזור שבו רוצים לשריין משאבים.

לדוגמה, כדי ליצור מקום שמור של עשר מכונות וירטואליות בתחום (zone) us-central1-a על ידי ציון תבנית של הגדרות מכונה גלובלית, מריצים את הפקודה הבאה:

gcloud compute reservations create my-reservation \
    --source-instance-template=example-instance-template \
    --vm-count=10 \
    --zone=us-central1-a

אפשר גם לבצע אחת או יותר מהפעולות הבאות:

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

    gcloud compute reservations create RESERVATION_NAME \
        --source-instance-template=INSTANCE_TEMPLATE_URL \
        --require-specific-reservation \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    
  • כדי לשמור מקום למכונות וירטואליות של GPU שמיועדות למשימות אימון בהתאמה אישית או למשימות חיזוי ב-Vertex AI, צריך להוסיף את האפשרות --reservation-sharing-policy עם הערך ALLOW_ALL.

    gcloud compute reservations create RESERVATION_NAME \
        --source-instance-template=INSTANCE_TEMPLATE_URL \
        --reservation-sharing-policy=ALLOW_ALL \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    
  • כדי לאפשר ל-Compute Engine למחוק אוטומטית את הבקשה לשמירת מקום, בוחרים אחת מהשיטות הבאות:

    • כדי למחוק את הבקשה לשמירת מקום בתאריך ובשעה ספציפיים, משתמשים בפקודה gcloud beta compute reservations create עם הדגל --delete-at-time.

      gcloud beta compute reservations create RESERVATION_NAME \
          --delete-at-time=DELETE_AT_TIME \
          --source-instance-template=INSTANCE_TEMPLATE_URL \
          --vm-count=NUMBER_OF_VMS \
          --zone=ZONE
      

      מחליפים את DELETE_AT_TIME בתאריך ובשעה בפורמט של חותמת זמן RFC 3339, שצריך להיות כזה: none YYYY-MM-DDTHH:MM:SSOFFSET

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

      • YYYY-MM-DD: תאריך בפורמט של שנה בת 4 ספרות, חודש בן 2 ספרות ויום בחודש בן 2 ספרות, מופרדים במקפים (-).

      • HH:MM:SS: שעה בפורמט של שעה בת 2 ספרות בפורמט של 24 שעות, דקות בנות 2 ספרות ושניות בנות 2 ספרות, מופרדות באמצעות נקודתיים (:).

      • OFFSET: אזור הזמן בפורמט של היסט מהזמן האוניברסלי המתואם (UTC). לדוגמה, כדי להשתמש בשעון החוף המערבי (PST), מציינים -08:00. לחלופין, כדי לא להשתמש בהזחה, מציינים Z.

    • כדי למחוק את ההזמנה אחרי משך זמן מסוים, משתמשים בפקודה gcloud beta compute reservations create עם הדגל --delete-after-duration.

      gcloud beta compute reservations create RESERVATION_NAME \
          --delete-after-duration=DELETE_AFTER_DURATION \
          --source-instance-template=INSTANCE_TEMPLATE_URL \
          --vm-count=NUMBER_OF_VMS \
          --zone=ZONE
      

      מחליפים את DELETE_AFTER_DURATION במשך הזמן בימים, בשעות, בדקות או בשניות. לדוגמה, מציינים 30m ל-30 דקות, או 1d2h3m4s ליום אחד, שעתיים, 3 דקות ו-4 שניות.

המשך

import (
	"context"
	"fmt"
	"io"

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

// Creates the reservation from given template in particular zone
func createReservation(w io.Writer, projectID, zone, reservationName, sourceTemplate string) error {
	// projectID := "your_project_id"
	// zone := "us-west3-a"
	// reservationName := "your_reservation_name"
	// template: 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()
	reservationsClient, err := compute.NewReservationsRESTClient(ctx)
	if err != nil {
		return err
	}
	defer reservationsClient.Close()

	req := &computepb.InsertReservationRequest{
		Project: projectID,
		ReservationResource: &computepb.Reservation{
			Name: proto.String(reservationName),
			Zone: proto.String(zone),
			SpecificReservation: &computepb.AllocationSpecificSKUReservation{
				Count:                  proto.Int64(2),
				SourceInstanceTemplate: proto.String(sourceTemplate),
			},
		},
		Zone: zone,
	}

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

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

	fmt.Fprintf(w, "Reservation created\n")

	return nil
}

Java

import com.google.cloud.compute.v1.AllocationSpecificSKUReservation;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Reservation;
import com.google.cloud.compute.v1.ReservationsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateReservationForInstanceTemplate {

  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 in which you want to create the reservation.
    String zone = "us-central1-a";
    // Name of the reservation you want to create.
    String reservationName = "YOUR_RESERVATION_NAME";
    // The number of virtual machines you want to create.
    int numberOfVms = 3;
    // The URI of the instance template with GLOBAL location
    // to be used for creating the reservation.
    String instanceTemplateUri =
        "projects/YOUR_PROJECT_ID/global/instanceTemplates/YOUR_INSTANCE_TEMPLATE_NAME";
    // The URI of the instance template with REGIONAL location
    // to be used for creating the reservation. For us-central1 region in this case.
    // String instanceTemplateUri =
    // "projects/YOUR_PROJECT_ID/regions/us-central1/instanceTemplates/YOUR_INSTANCE_TEMPLATE_NAME"

    createReservationForInstanceTemplate(
        projectId, reservationName, instanceTemplateUri, numberOfVms, zone);
  }

  // Creates a reservation in a project for the instance template.
  public static Reservation createReservationForInstanceTemplate(
      String projectId, String reservationName, String instanceTemplateUri,
      int numberOfVms, String zone)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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 (ReservationsClient reservationsClient = ReservationsClient.create()) {
      Reservation reservation =
          Reservation.newBuilder()
              .setName(reservationName)
              .setZone(zone)
              .setSpecificReservation(
                  AllocationSpecificSKUReservation.newBuilder()
                      // Set the number of instances
                      .setCount(numberOfVms)
                      // Set the instance template to be used for creating the reservation.
                      .setSourceInstanceTemplate(instanceTemplateUri)
                      .build())
              .build();

      Operation response =
          reservationsClient.insertAsync(projectId, zone, reservation).get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        return null;
      }
      return reservationsClient.get(projectId, zone, reservationName);
    }
  }
}

Node.js

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

// Instantiate a reservationsClient
const reservationsClient = new computeLib.ReservationsClient();
// 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 reserve resources and where the instance template exists.
const projectId = await reservationsClient.getProjectId();
// The zone in which to reserve resources.
const zone = 'us-central1-a';
// The name of the reservation to create.
// reservationName = 'reservation-01';
// The number of VMs to reserve.
const vmsNumber = 3;

/**
 * The name of an existing instance template.
 * TODO(developer): Uncomment and update instanceTemplateName before running the sample.
 */
// const instanceTemplateName = 'pernament-region-template-name';

/**
 * // The location of the instance template.
 * TODO(developer): Uncomment the `location` variable depending on which template you want to use.
 */

// The location for a regional instance template: regions/{region}. Replace region with the region where the instance template is located.
// If you specify a regional instance template, then you can only reserve VMs within the same region as the template's region.
// const location = `regions/${zone.slice(0, -2)}`;

// The location for a global instance template.
// const location = 'global';

async function callCreateComputeReservationInstanceTemplate() {
  // Create reservation for 3 VMs in zone us-central1-a by specifying a instance template.
  const specificReservation = new compute.AllocationSpecificSKUReservation({
    count: vmsNumber,
    sourceInstanceTemplate: `projects/${projectId}/${location}/instanceTemplates/${instanceTemplateName}`,
  });

  // Create a reservation.
  const reservation = new compute.Reservation({
    name: reservationName,
    specificReservation,
    // To specify that only VMs that specifically target this reservation can consume it,
    // set specificReservationRequired field to true.
    specificReservationRequired: true,
  });

  const [response] = await reservationsClient.insert({
    project: projectId,
    reservationResource: reservation,
    zone,
  });

  let operation = response.latestResponse;

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

  console.log(`Reservation: ${reservationName} created.`);
}

await callCreateComputeReservationInstanceTemplate();

Python

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def create_reservation_from_template(
    project_id: str, reservation_name: str, template: str
) -> compute_v1.Reservation:
    """
    Create a new reservation based on an existing template.

    Args:
        project_id: project ID or project number of the Cloud project you use.
        reservation_name: the name of new reservation.
        template: 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

    Returns:
        Reservation object that represents the new reservation.
    """

    reservations_client = compute_v1.ReservationsClient()
    request = compute_v1.InsertReservationRequest()
    request.project = project_id
    request.zone = "us-central1-a"

    specific_reservation = compute_v1.AllocationSpecificSKUReservation()
    specific_reservation.count = 1
    specific_reservation.source_instance_template = template

    reservation = compute_v1.Reservation()
    reservation.name = reservation_name
    reservation.specific_reservation = specific_reservation

    request.reservation_resource = reservation
    operation = reservations_client.insert(request)
    wait_for_extended_operation(operation, "Reservation creation")

    return reservations_client.get(
        project=project_id, zone="us-central1-a", reservation=reservation_name
    )

REST

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

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

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations

{
  "name": "RESERVATION_NAME",
  "specificReservation": {
    "count": "NUMBER_OF_VMS",
    "sourceInstanceTemplate": "INSTANCE_TEMPLATE_URL"
  }
}

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

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

  • ZONE: האזור שבו רוצים לשריין משאבים.

  • RESERVATION_NAME: השם של ההזמנה שרוצים ליצור.

  • NUMBER_OF_VMS: מספר המכונות הווירטואליות שרוצים לשריין.

  • INSTANCE_TEMPLATE_URL: כתובת ה-URL של תבנית קיימת של הגדרות מכונה. מציינים אחד מהערכים הבאים:

    • לתבנית של הגדרות מכונה אזורית: projects/PROJECT_ID/regions/REGION/instanceTemplates/INSTANCE_TEMPLATE_NAME

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

לדוגמה, כדי ליצור מקום שמור של עשר מכונות וירטואליות בתחום (zone) us-central1-a באמצעות תבנית של הגדרות מכונה גלובלית, שולחים את בקשת POST הבאה:

POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations

{
  "name": "my-reservation",
  "specificReservation": {
    "count": "10",
    "sourceInstanceTemplate": "example-instance-template"
  }
}

אפשר גם לבצע אחת או יותר מהפעולות הבאות:

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

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "sourceInstanceTemplate": "INSTANCE_TEMPLATE_URL"
      },
      "specificReservationRequired": true
    }
    
  • כדי לאפשר למשימות אימון בהתאמה אישית או למשימות חיזוי ב-Vertex AI להשתמש בשמירת מקום למכונות וירטואליות של GPU, צריך לכלול את השדה serviceShareType ולהגדיר אותו לערך ALLOW_ALL.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "reservationSharingPolicy": {
        "serviceShareType": "ALLOW_ALL"
      },
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "sourceInstanceTemplate": "INSTANCE_TEMPLATE_URL"
      }
    }
    
  • כדי לאפשר ל-Compute Engine למחוק אוטומטית את הבקשה לשמירת מקום, בוחרים אחת מהשיטות הבאות:

    • כדי למחוק את הבקשה לשמירת מקום בתאריך ובשעה מסוימים, שולחים POSTבקשה לשיטה beta.reservations.insert. בגוף הבקשה, כוללים את השדה deleteAtTime.

      POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations
      
      {
        "deleteAtTime": "DELETE_AT_TIME",
        "name": "RESERVATION_NAME",
        "specificReservation": {
          "count": "NUMBER_OF_VMS",
          "sourceInstanceTemplate": "INSTANCE_TEMPLATE_URL"
        }
      }
      

      מחליפים את DELETE_AT_TIME בתאריך ובשעה בפורמט של חותמת זמן RFC 3339, שצריך להיות כזה:

      YYYY-MM-DDTHH:MM:SSOFFSET
      

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

      • YYYY-MM-DD: תאריך בפורמט של שנה בת 4 ספרות, חודש בן 2 ספרות ויום בחודש בן 2 ספרות, מופרדים במקפים (-).

      • HH:MM:SS: שעה בפורמט של שעה בת 2 ספרות בפורמט של 24 שעות, דקות בנות 2 ספרות ושניות בנות 2 ספרות, מופרדות באמצעות נקודתיים (:).

      • OFFSET: אזור הזמן בפורמט של היסט מהזמן האוניברסלי המתואם (UTC). לדוגמה, כדי להשתמש בשעון החוף המערבי (PST), מציינים -08:00. לחלופין, כדי לא להשתמש בהזחה, מציינים Z.

    • כדי למחוק את ההזמנה אחרי משך זמן מסוים, שולחים POST בקשה לשיטה beta.reservations.insert. בגוף הבקשה, כוללים את השדה deleteAfterDuration.

      POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations
      
      {
        "deleteAfterDuration": {
          "seconds": "DELETE_AFTER_DURATION"
        },
        "name": "RESERVATION_NAME",
        "specificReservation": {
          "count": "NUMBER_OF_VMS",
          "sourceInstanceTemplate": "INSTANCE_TEMPLATE_URL"
        }
      }
      

      מחליפים את DELETE_AFTER_DURATION במשך הזמן בשניות. לדוגמה, מציינים 86400 ל-86,400 שניות (יום אחד).

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

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

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

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

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

    כניסה לדף Reservations

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

  3. נותנים לבקשה שם בשדה Name.

  4. ברשימות Region ו-Zone, בוחרים את האזור והתחום שבהם רוצים לשריין את המשאבים.

  5. אופציונלי: כדי לאפשר למשימות אימון בהתאמה אישית או למשימות חיזוי ב-Vertex AI להשתמש במכונות וירטואליות של GPU ששמורות במכסת השימוש, בקטע Google Cloud services בוחרים באפשרות Share reservation.

  6. בקטע Use with VM instance (שימוש עם מכונת VM), בוחרים באחת מהאפשרויות הבאות:

    • כדי להשתמש אוטומטית במכונות וירטואליות שמתאימות לפרטי הבקשה, מסמנים את האפשרות Use reservation automatically.

    • כדי להשתמש במשאבים שמתאימים לפרטי הבקשה רק כשיוצרים מכונות וירטואליות שמיועדות ספציפית אליה (לפי שם), בוחרים באפשרות Select specific reservation.

  7. בקטע Resource details (פרטי המשאב), מבצעים את הפעולות הבאות:

    • בשדה Number of VM instances, מקלידים את מספר המכונות הווירטואליות שרוצים לשריין.

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

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

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

      1. לוחצים על יצירת מדיניות למיקום קבוצות. מופיעה החלונית Create a group placement policy.

      2. בשדה Policy name, כותבים את השם של המדיניות.

      3. לוחצים על יצירה. יצירת המדיניות למיקום קומפקטי עשויה להימשך כמה שניות.

    • אחרת, בוחרים מדיניות קיימת למיקום קומפקטי.

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

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

ציון מאפיינים ישירות

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

המסוף

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

    כניסה לדף Reservations

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

  3. נותנים לבקשה שם בשדה Name.

  4. ברשימות Region ו-Zone, בוחרים את האזור והתחום שבהם רוצים לשריין את המשאבים.

  5. אופציונלי: כדי לאפשר למשימות אימון בהתאמה אישית או למשימות חיזוי ב-Vertex AI להשתמש במכונות וירטואליות של GPU ששמורות במכסת השימוש, בקטע Google Cloud services בוחרים באפשרות Share reservation.

  6. בקטע Use with VM instance (שימוש עם מכונת VM), בוחרים באחת מהאפשרויות הבאות:

    • כדי להשתמש אוטומטית במכונות וירטואליות שמתאימות לפרטי הבקשה, מסמנים את האפשרות Use reservation automatically.

    • כדי להשתמש במשאבים שמתאימים לפרטי הבקשה רק כשיוצרים מכונות וירטואליות שמיועדות ספציפית אליה (לפי שם), בוחרים באפשרות Select specific reservation.

  7. בקטע Resource details (פרטי המשאב), מבצעים את הפעולות הבאות:

    • בשדה Number of VM instances מקלידים את מספר המכונות הווירטואליות שרוצים לשריין.

    • מציינים את סדרת המכונות ואת הסוג שרוצים לשריין.

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

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

      1. לוחצים על יצירת מדיניות למיקום קבוצות. מופיעה החלונית Create a group placement policy.

      2. בשדה Policy name, כותבים את השם של המדיניות.

      3. לוחצים על יצירה. יצירת המדיניות למיקום קומפקטי עשויה להימשך כמה שניות.

    • אחרת, בוחרים מדיניות קיימת למיקום קומפקטי.

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

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

gcloud

כדי ליצור הזמנה לפרויקט יחיד, משתמשים בפקודה gcloud compute reservations create.

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

gcloud compute reservations create RESERVATION_NAME \
    --machine-type=MACHINE_TYPE \
    --vm-count=NUMBER_OF_VMS \
    --zone=ZONE

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

  • RESERVATION_NAME: השם של ההזמנה שרוצים ליצור.

  • MACHINE_TYPE: סוג המכונה לשימוש בכל מכונה וירטואלית.

  • NUMBER_OF_VMS: מספר המכונות הווירטואליות שרוצים לשריין.

  • ZONE: האזור שבו רוצים לשריין משאבים.

לדוגמה, כדי ליצור מקום שמור באזור us-central1-a לעשר מכונות וירטואליות שכל אחת מהן משתמשת בסוג מכונה עם קונפיגורציה מוגדרת (predefined) מסוג N2 עם 4 vCPU, מריצים את הפקודה הבאה:

gcloud compute reservations create my-reservation \
    --machine-type=n2-standard-4 \
    --vm-count=10 \
    --zone=us-central1-a

אפשר גם לבצע אחת או יותר מהפעולות הבאות:

  • כדי לצרף יחידות GPU למכונות וירטואליות מסוג N1 שהוזמנו, צריך לכלול את הדגל --accelerator.

    gcloud compute reservations create RESERVATION_NAME \
        --accelerator=count=NUMBER_OF_ACCELERATORS,type=ACCELERATOR_TYPE \
        --machine-type=MACHINE_TYPE \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    

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

  • כדי לצרף דיסקים של SSD מקומיים לסוג מכונה שלא כולל דיסקים של SSD מקומיים כברירת מחדל, צריך לכלול את הדגל --local-ssd. אפשר לצרף רק דיסקים מסוג Local SSD בנפח של 375GB.

    gcloud compute reservations create RESERVATION_NAME \
        --local-ssd=count=NUMBER_OF_LOCAL_SSD_DISKS,size=375,interface=INTERFACE_TYPE \
        --machine-type=MACHINE_TYPE \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    

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

    • NUMBER_OF_LOCAL_SSD_DISKS: מספר דיסקי ה-SSD המקומיים לצירוף.

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

      • לממשק הדיסק NVME: ‏ nvme

      • לממשק דיסק SCSI: scsi

  • כדי שמכונות ה-VM השמורות ישתמשו בפלטפורמת CPU מינימלית ספציפית במקום בפלטפורמת ה-CPU שמוגדרת כברירת מחדל לאזור, צריך לכלול את הדגל --min-cpu-platform.

    gcloud compute reservations create RESERVATION_NAME \
        --machine-type=MACHINE_TYPE \
        --min-cpu-platform="MIN_CPU_PLATFORM" \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    

    מחליפים את MIN_CPU_PLATFORM בפלטפורמת מעבד מינימלית. כדי לוודא שפלטפורמת CPU זמינה באזור שבו אתם מזמינים משאבים, אפשר לראות את פלטפורמות ה-CPU הזמינות לפי אזור.

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

    gcloud compute reservations create RESERVATION_NAME \
        --machine-type=MACHINE_TYPE \
        --require-specific-reservation \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    
  • כדי לציין מדיניות מיקום קומפקטית לזמן אחזור נמוך יותר ברשת בין מכונות וירטואליות, צריך לכלול את הדגל --resource-policies=policy.

    gcloud compute reservations create RESERVATION_NAME \
        --machine-type=MACHINE_TYPE \
        --resource-policies=policy=COMPACT_PLACEMENT_POLICY_NAME \
        --require-specific-reservation \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    

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

  • כדי לאפשר למשימות אימון בהתאמה אישית או למשימות חיזוי ב-Vertex AI להשתמש במכונות וירטואליות של GPU ששמורות, צריך לכלול את הדגל --reservation-sharing-policy עם הערך ALLOW_ALL.

    gcloud compute reservations create RESERVATION_NAME \
        --machine-type=MACHINE_TYPE \
        --reservation-sharing-policy=ALLOW_ALL \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    
  • כדי לאפשר ל-Compute Engine למחוק אוטומטית את הבקשה לשמירת מקום, בוחרים אחת מהשיטות הבאות:

    • כדי למחוק את הבקשה לשמירת מקום בתאריך ובשעה ספציפיים, משתמשים בפקודה gcloud beta compute reservations create עם הדגל --delete-at-time.

      gcloud beta compute reservations create RESERVATION_NAME \
          --delete-at-time=DELETE_AT_TIME \
          --machine-type=MACHINE_TYPE \
          --vm-count=NUMBER_OF_VMS \
          --zone=ZONE
      

      מחליפים את DELETE_AT_TIME בתאריך ובשעה בפורמט של חותמת זמן RFC 3339, שצריך להיות כזה:

      YYYY-MM-DDTHH:MM:SSOFFSET
      

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

      • YYYY-MM-DD: תאריך בפורמט של שנה בת 4 ספרות, חודש בן 2 ספרות ויום בחודש בן 2 ספרות, מופרדים במקפים (-).

      • HH:MM:SS: שעה בפורמט של שעה בת 2 ספרות בפורמט של 24 שעות, דקות בנות 2 ספרות ושניות בנות 2 ספרות, מופרדות באמצעות נקודתיים (:).

      • OFFSET: אזור הזמן בפורמט של היסט מהזמן האוניברסלי המתואם (UTC). לדוגמה, כדי להשתמש בשעון החוף המערבי (PST), מציינים -08:00. לחלופין, כדי לא להשתמש בהזחה, מציינים Z.

    • כדי למחוק את ההזמנה אחרי משך זמן מסוים, משתמשים בפקודה gcloud beta compute reservations create עם הדגל --delete-after-duration.

      gcloud beta compute reservations create RESERVATION_NAME \
          --delete-after-duration=DELETE_AFTER_DURATION \
          --machine-type=MACHINE_TYPE \
          --vm-count=NUMBER_OF_VMS \
          --zone=ZONE
      

      מחליפים את DELETE_AFTER_DURATION במשך הזמן בימים, בשעות, בדקות או בשניות. לדוגמה, מציינים 30m ל-30 דקות, או 1d2h3m4s ליום אחד, שעתיים, 3 דקות ו-4 שניות.

המשך

import (
	"context"
	"fmt"
	"io"

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

// Creates the reservation with accelerated image
func createBaseReservation(w io.Writer, projectID, zone, reservationName string) error {
	// projectID := "your_project_id"
	// zone := "us-west3-a"
	// reservationName := "your_reservation_name"

	ctx := context.Background()
	reservationsClient, err := compute.NewReservationsRESTClient(ctx)
	if err != nil {
		return err
	}
	defer reservationsClient.Close()

	// Creating reservation based on direct properties
	req := &computepb.InsertReservationRequest{
		Project: projectID,
		ReservationResource: &computepb.Reservation{
			Name: proto.String(reservationName),
			Zone: proto.String(zone),
			SpecificReservation: &computepb.AllocationSpecificSKUReservation{
				Count: proto.Int64(2),
				// Properties, which allows customising instances
				InstanceProperties: &computepb.AllocationSpecificSKUAllocationReservedInstanceProperties{
					// Attaching GPUs to the reserved VMs
					// Read more: https://cloud.google.com/compute/docs/gpus#n1-gpus
					GuestAccelerators: []*computepb.AcceleratorConfig{
						{
							AcceleratorCount: proto.Int32(1),
							AcceleratorType:  proto.String("nvidia-tesla-t4"),
						},
					},
					// Including local SSD disks
					LocalSsds: []*computepb.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk{
						{
							DiskSizeGb: proto.Int64(375),
							Interface:  proto.String("NVME"),
						},
					},
					MachineType: proto.String("n1-standard-2"),
					// Specifying minimum CPU platform
					// Read more: https://cloud.google.com/compute/docs/instances/specify-min-cpu-platform
					MinCpuPlatform: proto.String("Intel Skylake"),
				},
			},
		},
		Zone: zone,
	}

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

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

	fmt.Fprintf(w, "Reservation created\n")

	return nil
}

Java

import com.google.cloud.compute.v1.AcceleratorConfig;
import com.google.cloud.compute.v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk;
import com.google.cloud.compute.v1.AllocationSpecificSKUAllocationReservedInstanceProperties;
import com.google.cloud.compute.v1.AllocationSpecificSKUReservation;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Reservation;
import com.google.cloud.compute.v1.ReservationsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateReservation {

  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 in which you want to create the disk.
    String zone = "us-central1-a";
    // Name of the reservation you want to create.
    String reservationName = "YOUR_RESERVATION_NAME";
    // Number of instances in the reservation.
    int numberOfVms = 3;

    createReservation(projectId, reservationName, numberOfVms, zone);
  }

  // Creates reservation with optional flags
  public static Reservation createReservation(
      String projectId, String reservationName, int numberOfVms, String zone)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Create the reservation with optional properties:
    // Machine type of the instances in the reservation.
    String machineType = "n1-standard-2";
    // Number of accelerators to be attached to the instances in the reservation.
    int numberOfAccelerators = 1;
    // Accelerator type to be attached to the instances in the reservation.
    String acceleratorType = "nvidia-tesla-t4";
    // Minimum CPU platform to be attached to the instances in the reservation.
    String minCpuPlatform = "Intel Skylake";
    // Local SSD size in GB to be attached to the instances in the reservation.
    int localSsdSize = 375;
    // Local SSD interfaces to be attached to the instances in the reservation.
    String localSsdInterface1 = "NVME";
    String localSsdInterface2 = "SCSI";
    boolean specificReservationRequired = true;
    // 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 (ReservationsClient reservationsClient = ReservationsClient.create()) {
      Reservation reservation =
          Reservation.newBuilder()
              .setName(reservationName)
              .setZone(zone)
              .setSpecificReservationRequired(specificReservationRequired)
              .setSpecificReservation(
                  AllocationSpecificSKUReservation.newBuilder()
                      // Set the number of instances
                      .setCount(numberOfVms)
                      // Set instance properties
                      .setInstanceProperties(
                          AllocationSpecificSKUAllocationReservedInstanceProperties.newBuilder()
                              .setMachineType(machineType)
                              .setMinCpuPlatform(minCpuPlatform)
                              .addGuestAccelerators(
                                  AcceleratorConfig.newBuilder()
                                      .setAcceleratorCount(numberOfAccelerators)
                                      .setAcceleratorType(acceleratorType)
                                      .build())
                              .addLocalSsds(
                            AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk
                                      .newBuilder()
                                      .setDiskSizeGb(localSsdSize)
                                      .setInterface(localSsdInterface1)
                                      .build())
                              .addLocalSsds(
                            AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk
                                      .newBuilder()
                                      .setDiskSizeGb(localSsdSize)
                                      .setInterface(localSsdInterface2)
                                      .build())
                              .build())
                      .build())
              .build();

      Operation response =
          reservationsClient.insertAsync(projectId, zone, reservation).get(7, TimeUnit.MINUTES);

      if (response.hasError()) {
        return null;
      }
      return reservationsClient.get(projectId, zone, reservationName);
    }
  }
}

Node.js

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

// Instantiate a reservationsClient
const reservationsClient = new computeLib.ReservationsClient();
// 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 reserve resources.
const projectId = await reservationsClient.getProjectId();
// The zone in which to reserve resources.
const zone = 'us-central1-a';
// The name of the reservation to create.
// reservationName = 'reservation-01';
// The number of VMs to reserve.
const vmsNumber = 3;
// Machine type to use for each VM.
const machineType = 'n1-standard-4';

async function callCreateComputeReservationFromProperties() {
  // Create specific reservation for 3 VMs that each use an N1 predefined machine type with 4 vCPUs.
  const specificReservation = new compute.AllocationSpecificSKUReservation({
    count: vmsNumber,
    instanceProperties: {
      machineType,
      // To have the reserved VMs use a specific minimum CPU platform instead of the zone's default CPU platform.
      minCpuPlatform: 'Intel Skylake',
      // If you want to attach GPUs to your reserved N1 VMs, update and uncomment guestAccelerators if needed.
      // guestAccelerators: [
      //   {
      //     // The number of GPUs to add per reserved VM.
      //     acceleratorCount: 1,
      //     // Supported GPU model for N1 VMs. Ensure that your chosen GPU model is available in the zone,
      //     // where you want to reserve resources.
      //     acceleratorType: 'nvidia-tesla-t4',
      //   },
      // ],
      // If you want to add local SSD disks to each reserved VM, update and uncomment localSsds if needed.
      // You can specify up to 24 Local SSD disks. Each Local SSD disk is 375 GB.
      // localSsds: [
      //   {
      //     diskSizeGb: 375,
      //     // The type of interface you want each Local SSD disk to use. Specify one of the following values: NVME or SCSI.
      //     // Make sure that the machine type you specify for the reserved VMs supports the chosen disk interfaces.
      //     interface: 'NVME',
      //   },
      // ],
    },
  });

  // Create a reservation.
  const reservation = new compute.Reservation({
    name: reservationName,
    zone,
    specificReservation,
    // To specify that only VMs that specifically target this reservation can consume it,
    // set specificReservationRequired field to true.
    specificReservationRequired: true,
  });

  const [response] = await reservationsClient.insert({
    project: projectId,
    reservationResource: reservation,
    zone,
  });

  let operation = response.latestResponse;

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

  console.log(`Reservation: ${reservationName} created.`);
}

await callCreateComputeReservationFromProperties();

Python

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def create_compute_reservation(
    project_id: str,
    zone: str = "us-central1-a",
    reservation_name="your-reservation-name",
) -> compute_v1.Reservation:
    """Creates a compute reservation in GCP.
    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.
    Returns:
        Reservation object that represents the new reservation.
    """

    instance_properties = compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
        machine_type="n1-standard-1",
        # Optional. Specifies the minimum CPU platform for the VM instance.
        min_cpu_platform="Intel Ivy Bridge",
        # Optional. Specifies amount of local ssd to reserve with each instance.
        local_ssds=[
            compute_v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk(
                disk_size_gb=375, interface="NVME"
            ),
            compute_v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk(
                disk_size_gb=375, interface="SCSI"
            ),
        ],
        # Optional. Specifies the GPUs allocated to each instance.
        # guest_accelerators=[
        #     compute_v1.AcceleratorConfig(
        #         accelerator_count=1, accelerator_type="nvidia-tesla-t4"
        #     )
        # ],
    )

    reservation = compute_v1.Reservation(
        name=reservation_name,
        specific_reservation=compute_v1.AllocationSpecificSKUReservation(
            count=3,  # Number of resources that are allocated.
            # If you use source_instance_template, you must exclude the instance_properties field.
            # It can be a full or partial URL.
            # source_instance_template="projects/[PROJECT_ID]/global/instanceTemplates/my-instance-template",
            instance_properties=instance_properties,
        ),
    )

    # Create a client
    client = compute_v1.ReservationsClient()

    operation = client.insert(
        project=project_id,
        zone=zone,
        reservation_resource=reservation,
    )
    wait_for_extended_operation(operation, "Reservation creation")

    reservation = client.get(
        project=project_id, zone=zone, reservation=reservation_name
    )

    print("Name: ", reservation.name)
    print("STATUS: ", reservation.status)
    print(reservation.specific_reservation)
    # Example response:
    # Name:  your-reservation-name
    # STATUS:  READY
    # count: 3
    # instance_properties {
    #   machine_type: "n1-standard-1"
    #   local_ssds {
    #     disk_size_gb: 375
    #     interface: "NVME"
    #   }
    # ...

    return reservation

Terraform

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

לדוגמה, כדי ליצור שריון מקום שמור לפרויקט מסוים עבור סוג מכונה מוגדר מראש N2 עם 2 vCPU, משתמשים במשאב הבא:


resource "google_compute_reservation" "default" {
  name = "gce-reservation-local"
  zone = "us-central1-a"

  /**
   * To specify a single-project reservation, omit the share_settings block
   * (default) or set the share_type field to LOCAL.
   */
  share_settings {
    share_type = "LOCAL"
  }

  specific_reservation {
    count = 1
    instance_properties {
      machine_type = "n2-standard-2"
    }
  }

  /**
   * To let VMs with affinity for any reservation consume this reservation, omit
   * the specific_reservation_required field (default) or set it to false.
   */
  specific_reservation_required = false
}

מידע נוסף על השימוש ב-Terraform זמין במאמר שימוש ב-Terraform עם Cloud de Confiance by S3NS.

REST

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

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

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations

{
  "name": "RESERVATION_NAME",
  "specificReservation": {
    "count": "NUMBER_OF_VMS",
    "instanceProperties": {
      "machineType": "MACHINE_TYPE"
    }
  }
}

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

  • PROJECT_ID: מזהה הפרויקט שבו רוצים לשריין משאבים.

  • ZONE: האזור שבו רוצים לשריין משאבים.

  • RESERVATION_NAME: השם של ההזמנה שרוצים ליצור.

  • NUMBER_OF_VMS: מספר המכונות הווירטואליות שרוצים לשריין.

  • MACHINE_TYPE: סוג המכונה לשימוש בכל מכונה וירטואלית.

לדוגמה, כדי ליצור מקום שמור באזור us-central1-a ל-10 מכונות וירטואליות שכל אחת מהן משתמשת במכונה עם קונפיגורציה מוגדרת (predefined) מסוג N2 עם 4 vCPU, שולחים את בקשת POST הבאה:

POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations

{
  "name": "my-reservation",
  "specificReservation": {
    "count": "10",
    "instanceProperties": {
      "machineType": "n2-standard-4",
    }
  }
}

אפשר גם לבצע אחת או יותר מהפעולות הבאות:

  • כדי לצרף יחידות GPU למכונות וירטואליות מסוג N1 שהוזמנו, צריך לכלול את השדה guestAccelerators בגוף הבקשה.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "instanceProperties": {
          "guestAccelerators": [
            {
              "acceleratorCount": NUMBER_OF_ACCELERATORS,
              "acceleratorType": "ACCELERATOR_TYPE"
            }
          ],
          "machineType": "MACHINE_TYPE"
        }
      }
    }
    

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

  • כדי לצרף דיסקים של SSD מקומי לסוג מכונה שלא כולל דיסקים של SSD מקומי כברירת מחדל, צריך לכלול את השדה localSsds בגוף הבקשה. אפשר לצרף רק דיסקים מקומיים מסוג SSD בנפח של 375 GB.

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

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "instanceProperties": {
          "localSsds": [
            {
              "diskSizeGb": "375",
              "interface": "INTERFACE_TYPE"
            },
            {
              "diskSizeGb": "375",
              "interface": "INTERFACE_TYPE"
            }
          ],
          "machineType": "MACHINE_TYPE"
        }
      }
    }
    

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

    • לממשק הדיסק NVME: ‏ NVME

    • לממשק דיסק SCSI: SCSI

  • כדי שמכונות ה-VM השמורות ישתמשו בפלטפורמת CPU מינימלית ספציפית במקום בפלטפורמת ה-CPU שמוגדרת כברירת מחדל לאזור, צריך לכלול את השדה minCpuPlatform בגוף הבקשה.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "instanceProperties": {
          "machineType": "MACHINE_TYPE",
          "minCpuPlatform": "MIN_CPU_PLATFORM"
        }
      }
    }
    

    מחליפים את MIN_CPU_PLATFORM בפלטפורמת מעבד מינימלית. כדי לוודא שפלטפורמת CPU זמינה באזור שבו אתם מזמינים משאבים, אפשר לראות את פלטפורמות ה-CPU הזמינות לפי אזור.

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

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "resourcePolicies": {
        "policy" : "projects/PROJECT_ID/regions/REGION/resourcePolicies/COMPACT_PLACEMENT_POLICY_NAME"
      },
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "instanceProperties": {
          "machineType": "MACHINE_TYPE"
        }
      },
      "specificReservationRequired": true
    }
    

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

    • REGION: האזור שבו נמצאת מדיניות המיקום הקומפקטי. אפשר ליצור את ההזמנה רק באזור של מדיניות מיקומי המודעות.

    • COMPACT_PLACEMENT_POLICY_NAME: השם של מדיניות קיימת למיקום קומפקטי.

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

    • סוג מכונה נתמך למדיניות למיקום קומפקטי.

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

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

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "instanceProperties": {
          "machineType": "MACHINE_TYPE"
        }
      },
      "specificReservationRequired": true
    }
    
  • כדי לשמור מקום למכונות וירטואליות של GPU שמיועדות למשימות אימון בהתאמה אישית או למשימות חיזוי של Vertex AI, צריך לכלול את השדה serviceShareType ולהגדיר אותו לערך ALLOW_ALL.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "reservationSharingPolicy": {
        "serviceShareType": "ALLOW_ALL"
      },
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "instanceProperties": {
          "machineType": "MACHINE_TYPE"
        }
      }
    }
    
  • כדי לאפשר ל-Compute Engine למחוק אוטומטית את הבקשה לשמירת מקום, בוחרים אחת מהשיטות הבאות:

    • כדי למחוק את הבקשה לשמירת מקום בתאריך ובשעה מסוימים, שולחים POSTבקשה לשיטה beta.reservations.insert. בגוף הבקשה, כוללים את השדה deleteAtTime.

      POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations
      
      {
        "deleteAtTime": "DELETE_AT_TIME",
        "name": "RESERVATION_NAME",
        "specificReservation": {
          "count": "NUMBER_OF_VMS",
          "instanceProperties": {
            "machineType": "MACHINE_TYPE"
          }
        }
      }
      

      מחליפים את DELETE_AT_TIME בתאריך ובשעה בפורמט של חותמת זמן RFC 3339, שצריך להיות כזה:

      YYYY-MM-DDTHH:MM:SSOFFSET
      

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

      • YYYY-MM-DD: תאריך בפורמט של שנה בת 4 ספרות, חודש בן 2 ספרות ויום בחודש בן 2 ספרות, מופרדים במקפים (-).

      • HH:MM:SS: שעה בפורמט של שעה בת 2 ספרות בפורמט של 24 שעות, דקות בנות 2 ספרות ושניות בנות 2 ספרות, מופרדות באמצעות נקודתיים (:).

      • OFFSET: אזור הזמן בפורמט של היסט מהזמן האוניברסלי המתואם (UTC). לדוגמה, כדי להשתמש בשעון החוף המערבי (PST), מציינים -08:00. לחלופין, כדי לא להשתמש בהזחה, מציינים Z.

    • כדי למחוק את ההזמנה אחרי משך זמן מסוים, שולחים POST בקשה לשיטה beta.reservations.insert. בגוף הבקשה, כוללים את השדה deleteAfterDuration.

      POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations
      
      {
        "deleteAfterDuration": {
          "seconds": "DELETE_AFTER_DURATION"
        },
        "name": "RESERVATION_NAME",
        "specificReservation": {
          "count": "NUMBER_OF_VMS",
          "instanceProperties": {
            "machineType": "MACHINE_TYPE"
          }
        }
      }
      

      מחליפים את DELETE_AFTER_DURATION במשך הזמן בשניות. לדוגמה, מציינים 86400 ל-86,400 שניות (יום אחד).

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