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

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

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

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

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

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

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

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

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

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

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

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

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

יצירת מקום שמור לפרויקט יחיד

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

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

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

  • הגדרת מכונה וירטואלית קיימת

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

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

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

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

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

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

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

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

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

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

המסוף

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

    כניסה לדף 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, בוחרים אחת מהאפשרויות הבאות:

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

לדוגמה, כדי ליצור הקצאה ל-10 מכונות וירטואליות באזור 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

לדוגמה, כדי ליצור מקום שמור ל-10 מכונות וירטואליות באזור 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 ל-method 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 אל ה-method‏ 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 במסוף Google Cloud .

    כניסה לדף 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, בוחרים אחת מהאפשרויות הבאות:

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

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

  7. בקטע Resource details:

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

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

  8. אופציונלי: כדי לציין מדיניות מיקום קומפקטי להזמנה שעומדת בדרישות, בקטע Group placement policy לוחצים על הרשימה Select or create a group placement policy ואז מבצעים אחת מהפעולות הבאות:

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

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

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

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

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

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

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

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

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

המסוף

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

    כניסה לדף 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, בוחרים אחת מהאפשרויות הבאות:

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

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

  7. בקטע Resource details:

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

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

  8. אופציונלי: כדי לציין מדיניות מיקום קומפקטי להזמנה שעומדת בדרישות ההזמנה, בקטע Group placement policy לוחצים על הרשימה Select or create a group placement policy ומבצעים אחת מהפעולות הבאות:

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

      1. לוחצים על Create group placement policy. מופיע החלונית 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: סוג המכונה שבה משתמשים לכל VM.

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

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

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

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
    

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

  • כדי לצרף דיסקים מסוג Local SSD לסוג מכונה שלא כולל דיסקים מסוג Local 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

  • כדי שהמכונות הווירטואליות השמורות ישתמשו בפלטפורמת 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 מינימלית. כדי לוודא שפלטפורמת המעבד זמינה באזור שבו אתם שומרים משאבים, הציגו את פלטפורמות המעבד הזמינות לפי אזור.

  • כדי לציין שרק מכונות וירטואליות שמיועדות ספציפית לבקשה הזו יכולות להשתמש בה, צריך לכלול את הדגל --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

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

לדוגמה, כדי ליצור מקום שמור לפרויקט יחיד למכונה אחת עם קונפיגורציה מוגדרת (predefined) מסוג N2 עם 2 vCPUs, משתמשים במשאב הבא:


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

  /**
   * 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 = "e2-micro"
    }
  }

  /**
   * 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 עם Google Cloud.

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: סוג המכונה שבה משתמשים לכל VM.

לדוגמה, כדי ליצור מקום שמור באזור us-central1-a ל-10 מכונות וירטואליות, שכל אחת מהן משתמשת במכונה עם קונפיגורציה מוגדרת (predefined) מסוג N2 עם 4 vCPUs, שולחים את בקשת ה-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 בגוף הבקשה. אפשר לצרף רק דיסקים מסוג Local SSD בנפח של 375GB.

    לדוגמה, כדי לצרף שני דיסקים מסוג Local 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

  • כדי שהמכונות הווירטואליות השמורות ישתמשו בפלטפורמת 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 מינימלית. כדי לוודא שפלטפורמת המעבד זמינה באזור שבו אתם שומרים משאבים, הציגו את פלטפורמות המעבד הזמינות לפי אזור.

  • כדי לציין מדיניות מיקום קומפקטי לצמצום זמן האחזור ברשת בין המכונות הווירטואליות השמורות, צריך לכלול את השדה 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 ל-method 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 אל ה-method‏ 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 שניות (יום אחד).

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