Membuat pemesanan untuk satu project


Dokumen ini menjelaskan cara membuat pemesanan satu project, yang hanya dapat digunakan oleh instance virtual machine (VM) dalam project yang sama. Untuk mempelajari pemesanan lebih lanjut, lihat Pemesanan resource zona Compute Engine.

Untuk metode pembuatan pemesanan yang lain, lihat halaman berikut:

  • Untuk membuat pemesanan yang dapat digunakan oleh beberapa project, lihat Membuat pemesanan bersama.

  • Untuk membuat reservasi saat membeli komitmen berbasis resource, lihat Membeli komitmen dengan reservasi terlampir. Komitmen memberikan diskon, yang dikenal sebagai diskon abonemen (DA), untuk biaya resource sesuai permintaan Anda sebagai imbalan atas pembelian tingkat minimum resource atau pembelanjaan jumlah minimum.

Sebelum memulai

  • Tinjau persyaratan dan pembatasan untuk pemesanan.
  • Jika Anda belum melakukannya, siapkan autentikasi. Autentikasi adalah proses yang digunakan untuk memverifikasi identitas Anda untuk mengakses Google Cloud layanan dan API. Untuk menjalankan kode atau sampel dari lingkungan pengembangan lokal, Anda dapat melakukan autentikasi ke Compute Engine dengan memilih salah satu opsi berikut:

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

      1. After installing the Google Cloud CLI, initialize it by running the following command:

        gcloud init

        If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      2. Set a default region and zone.
      3. Terraform

        Untuk menggunakan contoh Terraform di halaman ini dalam lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

        1. Install the Google Cloud CLI.

        2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

        3. To initialize the gcloud CLI, run the following command:

          gcloud init
        4. If you're using a local shell, then create local authentication credentials for your user account:

          gcloud auth application-default login

          You don't need to do this if you're using Cloud Shell.

          If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

        Untuk informasi selengkapnya, lihat Set up authentication for a local development environment.

        REST

        Untuk menggunakan contoh REST API di halaman ini dalam lingkungan pengembangan lokal, gunakan kredensial yang Anda berikan ke gcloud CLI.

          After installing the Google Cloud CLI, initialize it by running the following command:

          gcloud init

          If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

        Untuk mengetahui informasi selengkapnya, lihat Melakukan autentikasi untuk menggunakan REST dalam dokumentasi autentikasi Google Cloud .

Peran yang diperlukan

Untuk mendapatkan izin yang diperlukan untuk membuat pemesanan satu project, minta administrator Anda untuk memberi Anda peran IAM Compute Admin (roles/compute.admin) di project. Untuk mengetahui informasi selengkapnya tentang cara memberikan peran, lihat Mengelola akses ke project, folder, dan organisasi.

Peran bawaan ini berisi izin yang diperlukan untuk membuat pemesanan satu project. Untuk melihat izin yang benar-benar diperlukan, luaskan bagian Izin yang diperlukan:

Izin yang diperlukan

Izin berikut diperlukan untuk membuat pemesanan satu project:

  • compute.reservations.create di project
  • Untuk menentukan template instance: compute.instanceTemplates.useReadOnly pada template instance

Anda mungkin juga bisa mendapatkan izin ini dengan peran khusus atau peran bawaan lainnya.

Membuat pemesanan satu project

Untuk menggunakan pemesanan, VM harus memiliki properti yang sama persis dengan pemesanan tersebut. Untuk menentukan properti VM yang ingin Anda pesan, pilih salah satu bagian berikut dalam dokumen ini:

  • Direkomendasikan: Menentukan template instance

    Bagian ini menjelaskan cara menggunakan template instance untuk menentukan properti pemesanan. Dengan menggunakan template instance, Anda dapat menentukan properti pemesanan dan VM yang dapat menggunakan pemesanan di tempat yang sama.

  • Tentukan VM yang ada

    Bagian ini menjelaskan cara menggunakan VM yang ada untuk menentukan properti pemesanan. Dengan menggunakan properti VM yang ada, Anda dapat menggunakan reservasi dengan membuat VM dengan properti yang cocok dengan VM referensi.

  • Menentukan properti secara langsung

    Bagian ini menjelaskan cara menentukan properti pemesanan secara langsung. Metode ini mengharuskan Anda secara manual memastikan bahwa properti VM dan pemesanan Anda sama persis—setiap properti yang tidak cocok akan mencegah pemakaian.

Secara default, pemesanan dapat otomatis dipakai oleh semua VM yang memiliki properti yang sama persis dengannya. Jika Anda ingin mengontrol pemakaian pemesanan, lakukan satu atau beberapa hal berikut:

Selain itu, Anda dapat menentukan kebijakan penempatan rapat saat membuat pemesanan khusus satu project. Kebijakan penempatan rapat menentukan bahwa VM harus ditempatkan sedekat mungkin satu sama lain untuk mengurangi latensi jaringan.

Menentukan template instance

Untuk menghindari error saat membuat pemesanan dengan menentukan template instance, pastikan hal berikut:

  • Buat pemesanan di region dan zona yang sama dengan resource dalam template instance. Setiap resource regional atau resource zona yang ditentukan dalam template instance—seperti jenis mesin atau volume Disk Persisten—membatasi penggunaan template ke lokasi tempat resource tersebut berada. Misalnya, jika template instance Anda menentukan volume Persistent Disk yang ada di zona us-central1-a, Anda hanya dapat membuat reservasi di zona yang sama. Untuk memeriksa apakah template yang ada menentukan resource yang mengikat template ke region atau zona tertentu, lihat detail template instance dan cari referensi ke resource regional atau resource zona di dalamnya.

  • Jika template instance menentukan kebijakan penempatan yang ringkas, pastikan template tersebut menentukan jenis mesin yang didukung untuk kebijakan penempatan yang ringkas. Jika tidak, pembuatan pemesanan akan gagal.

Untuk membuat pemesanan satu project dengan menentukan template instance, pilih salah satu opsi berikut:

Konsol

  1. Di konsol Google Cloud , buka halaman Reservations.

    Buka Pemesanan

  2. Di tab Reservasi sesuai permintaan (default), klik Buat reservasi.

    Halaman Create a reservation akan terbuka.

  3. Untuk Name, masukkan nama untuk reservasi Anda.

  4. Untuk Region dan Zone, pilih tempat Anda ingin memesan resource.

  5. Di bagian Jenis berbagi, pilih Lokal jika belum dipilih.

  6. Opsional: Untuk mengizinkan penggunaan reservasi VM GPU oleh tugas pelatihan kustom atau tugas prediksi di Vertex AI, di bagian Layanan Google Cloud, pilih Bagikan reservasi.

  7. Di bagian Gunakan dengan instance VM, pilih salah satu opsi berikut:

    • Untuk mengizinkan VM yang cocok menggunakan pemesanan ini secara otomatis, pilih Gunakan pemesanan secara otomatis jika belum dipilih.

    • Untuk menggunakan resource pemesanan ini hanya saat membuat VM yang sama persis yang secara khusus menargetkan pemesanan ini berdasarkan nama, pilih Pilih pemesanan tertentu.

  8. Untuk Number of VM instances, masukkan jumlah VM yang ingin Anda pesan.

  9. Di bagian Machine configuration, lakukan hal berikut:

    1. Untuk menentukan properti VM Anda dari template instance yang ada, pilih Gunakan template instance.

    2. Di kolom Template instance, pilih template instance pilihan Anda. Jika memilih template instance regional, Anda hanya dapat memesan resource dalam region template instance.

  10. Di bagian Hapus otomatis, Anda dapat mengaktifkan opsi hapus otomatis agar Compute Engine menghapus pemesanan secara otomatis pada tanggal dan waktu tertentu. Menghapus reservasi secara otomatis dapat berguna untuk menghindari biaya yang tidak perlu saat Anda berhenti menggunakan reservasi.

  11. Untuk membuat pemesanan, klik Buat.

    Halaman Reservations akan terbuka. Pembuatan pemesanan satu project dapat memakan waktu hingga satu menit.

gcloud

Untuk membuat reservasi satu project, gunakan perintah gcloud compute reservations create.

Untuk membuat pemesanan satu project dengan menentukan template instance dan tanpa menyertakan flag opsional, jalankan perintah berikut:

gcloud compute reservations create RESERVATION_NAME \
    --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \
    --vm-count=NUMBER_OF_VMS \
    --zone=ZONE

Ganti kode berikut:

  • RESERVATION_NAME: nama pemesanan yang akan dibuat.

  • PROJECT_ID: ID project tempat Anda ingin mencadangkan resource dan tempat template instance berada.

  • LOCATION: lokasi template instance. Tentukan salah satu nilai berikut:

    • Untuk template instance global: global.

    • Untuk template instance regional: regions/REGION. Ganti REGION dengan region tempat template instance berada. Jika Anda menentukan template instance regional, Anda hanya dapat memesan VM dalam region yang sama dengan region template.

  • INSTANCE_TEMPLATE_NAME: nama template instance yang ada. Jika template instance menentukan jenis mesin A3 Mega, A3 High, atau A3 Edge, atau kebijakan penempatan yang ringkas, Anda harus menyertakan flag --require-specific-reservation. Hal ini menunjukkan bahwa hanya VM yang secara khusus menargetkan reservasi yang dapat menggunakannya. Untuk mengetahui informasi selengkapnya, lihat Menggunakan VM dari reservasi tertentu.

  • NUMBER_OF_VMS: jumlah VM yang akan dipesan.

  • ZONE: zona tempat memesan resource.

Misalnya, untuk membuat reservasi untuk sepuluh VM di zona us-central1-a dengan menentukan template instance global, jalankan perintah berikut:

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

Secara opsional, Anda dapat melakukan satu atau beberapa hal berikut:

  • Untuk menentukan bahwa hanya VM yang secara khusus menargetkan reservasi ini yang dapat menggunakannya, sertakan flag --require-specific-reservation.

    gcloud compute reservations create RESERVATION_NAME \
        --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \
        --require-specific-reservation \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    
  • Untuk mengizinkan pemesanan VM GPU digunakan oleh tugas pelatihan kustom atau tugas prediksi di Vertex AI, sertakan flag --reservation-sharing-policy yang ditetapkan ke ALLOW_ALL.

    gcloud compute reservations create RESERVATION_NAME \
        --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \
        --reservation-sharing-policy=ALLOW_ALL \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    
  • Agar Compute Engine dapat menghapus pemesanan secara otomatis, pilih salah satu metode berikut:

    • Untuk menghapus reservasi pada tanggal dan waktu tertentu, gunakan perintah gcloud beta compute reservations create dengan flag --delete-at-time.

      gcloud beta compute reservations create RESERVATION_NAME \
          --delete-at-time=DELETE_AT_TIME \
          --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \
          --vm-count=NUMBER_OF_VMS \
          --zone=ZONE
      

      Ganti DELETE_AT_TIME dengan tanggal dan waktu yang diformat sebagai stempel waktu RFC 3339, yang harus seperti berikut: none YYYY-MM-DDTHH:MM:SSOFFSET

      Ganti kode berikut:

      • YYYY-MM-DD: tanggal yang diformat sebagai tahun 4 digit, bulan 2 digit, dan hari 2 digit dalam bulan, yang dipisahkan oleh tanda hubung (-).

      • HH:MM:SS: waktu yang diformat sebagai jam 2 digit menggunakan waktu 24 jam, menit 2 digit, dan detik 2 digit, yang dipisahkan oleh titik dua (:).

      • OFFSET: zona waktu yang diformat sebagai offset dari Waktu Universal Terkoordinasi (UTC). Misalnya, untuk menggunakan Waktu Standar Pasifik (PST), tentukan -08:00. Atau, untuk tidak menggunakan penyeimbang, tentukan Z.

    • Untuk menghapus pemesanan setelah durasi tertentu, gunakan perintah gcloud beta compute reservations create dengan flag --delete-after-duration.

      gcloud beta compute reservations create RESERVATION_NAME \
          --delete-after-duration=DELETE_AFTER_DURATION \
          --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \
          --vm-count=NUMBER_OF_VMS \
          --zone=ZONE
      

      Ganti DELETE_AFTER_DURATION dengan durasi dalam hari, jam, menit, atau detik. Misalnya, tentukan 30m selama 30 menit, atau 1d2h3m4s untuk 1 hari, 2 jam, 3 menit, dan 4 detik.

Go

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

Untuk membuat pemesanan satu project, buat permintaan POST ke metode reservations.insert.

Untuk membuat pemesanan satu project dengan menentukan template instance dan tanpa menyertakan flag opsional apa pun, buat permintaan POST berikut:

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

{
  "name": "RESERVATION_NAME",
  "specificReservation": {
    "count": "NUMBER_OF_VMS",
    "sourceInstanceTemplate": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"
  }
}

Ganti kode berikut:

  • PROJECT_ID: ID project tempat Anda ingin mencadangkan resource dan tempat template instance berada.

  • ZONE: zona tempat memesan resource.

  • RESERVATION_NAME: nama pemesanan yang akan dibuat.

  • NUMBER_OF_VMS: jumlah VM yang akan dipesan.

  • LOCATION: lokasi template instance. Tentukan salah satu nilai berikut:

    • Untuk template instance global: global.

    • Untuk template instance regional: regions/REGION. Ganti REGION dengan region tempat template instance berada. Jika Anda menentukan template instance regional, Anda hanya dapat memesan VM dalam region yang sama dengan region template.

  • INSTANCE_TEMPLATE_NAME: nama template instance yang ada. Jika template instance menentukan jenis mesin A3 Mega, A3 High, atau A3 Edge atau kebijakan penempatan ringkas, Anda harus menyertakan kolom specificReservationRequired di isi permintaan, dan menetapkan kolom ke true. Hal ini menunjukkan bahwa hanya VM yang secara khusus menargetkan reservasi ini yang dapat menggunakannya. Untuk mengetahui informasi selengkapnya, lihat Menggunakan VM dari reservasi tertentu.

Misalnya, untuk membuat reservasi sepuluh VM di zona us-central1-a dengan menentukan template instance global, buat permintaan POST berikut:

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

{
  "name": "my-reservation",
  "specificReservation": {
    "count": "10",
    "sourceInstanceTemplate": "projects/example-project/global/instanceTemplates/example-instance-template"
  }
}

Secara opsional, Anda dapat melakukan satu atau beberapa hal berikut:

  • Untuk menentukan bahwa hanya VM yang secara khusus menargetkan pemesanan ini yang dapat menggunakannya, sertakan kolom specificReservationRequired dalam isi permintaan, dan tetapkan kolom ke true.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "sourceInstanceTemplate": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"
      },
      "specificReservationRequired": true
    }
    
  • Untuk mengizinkan reservasi VM GPU digunakan oleh tugas pelatihan kustom atau tugas prediksi di Vertex AI, sertakan kolom serviceShareType dan tetapkan ke 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": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"
      }
    }
    
  • Agar Compute Engine dapat menghapus pemesanan secara otomatis, pilih salah satu metode berikut:

    • Untuk menghapus pemesanan pada tanggal dan waktu tertentu, buat permintaan POST ke metode beta.reservations.insert. Dalam isi permintaan, sertakan kolom 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": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"
        }
      }
      

      Ganti DELETE_AT_TIME dengan tanggal dan waktu yang diformat sebagai stempel waktu RFC 3339, yang harus seperti berikut:

      YYYY-MM-DDTHH:MM:SSOFFSET
      

      Ganti kode berikut:

      • YYYY-MM-DD: tanggal yang diformat sebagai tahun 4 digit, bulan 2 digit, dan hari 2 digit dalam bulan, yang dipisahkan oleh tanda hubung (-).

      • HH:MM:SS: waktu yang diformat sebagai jam 2 digit menggunakan waktu 24 jam, menit 2 digit, dan detik 2 digit, yang dipisahkan oleh titik dua (:).

      • OFFSET: zona waktu yang diformat sebagai offset dari Waktu Universal Terkoordinasi (UTC). Misalnya, untuk menggunakan Waktu Standar Pasifik (PST), tentukan -08:00. Atau, untuk tidak menggunakan penyeimbang, tentukan Z.

    • Untuk menghapus pemesanan setelah durasi tertentu, buat permintaan POST ke metode beta.reservations.insert. Dalam isi permintaan, sertakan kolom 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": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"
        }
      }
      

      Ganti DELETE_AFTER_DURATION dengan durasi dalam detik. Misalnya, tentukan 86400 untuk 86.400 detik (1 hari).

Menentukan VM yang ada

Anda hanya dapat membuat reservasi berdasarkan VM yang ada di zona yang sama dengan VM.

Setelah membuat reservasi, Anda dapat menggunakannya dengan membuat VM yang memiliki properti yang cocok dengan VM referensi. Anda dapat melakukannya dengan melakukan salah satu tindakan berikut:

Untuk membuat reservasi satu project yang menggunakan properti VM yang ada, lakukan hal berikut:

  1. Di konsol Google Cloud , buka halaman Reservations.

    Buka Pemesanan

  2. Klik Create reservation.

    Halaman Create a reservation akan terbuka.

  3. Untuk Name, masukkan nama untuk reservasi Anda.

  4. Untuk Region dan Zone, pilih tempat Anda ingin memesan resource.

  5. Di bagian Jenis berbagi, klik Lokal jika belum dipilih.

  6. Di bagian Gunakan dengan instance VM, pilih salah satu opsi berikut:

    • Untuk mengizinkan VM yang cocok menggunakan pemesanan ini secara otomatis, pilih Gunakan pemesanan secara otomatis jika belum dipilih.

    • Untuk menggunakan resource pemesanan ini hanya saat membuat VM yang sama persis yang secara khusus menargetkan pemesanan ini berdasarkan nama, pilih Pilih pemesanan tertentu.

  7. Untuk Number of VM instances, masukkan jumlah VM yang ingin Anda pesan.

  8. Di bagian Machine configuration, lakukan hal berikut:

    1. Pilih Gunakan VM yang ada.

    2. Untuk VM yang Ada, pilih VM yang propertinya ingin Anda gunakan untuk membuat reservasi.

  9. Opsional: Untuk menentukan kebijakan penempatan ringkas untuk reservasi yang memenuhi persyaratan, di bagian Kebijakan penempatan grup, klik daftar Pilih atau buat kebijakan penempatan grup, lalu lakukan salah satu tindakan berikut:

    • Untuk membuat kebijakan penempatan rapat yang akan ditentukan dalam pemesanan ini, lakukan hal berikut:

      1. Klik Create group placement policy.

        Panel Buat kebijakan penempatan grup akan muncul.

      2. Untuk Nama kebijakan, masukkan nama kebijakan Anda.

      3. Klik Buat.

        Mungkin perlu waktu beberapa detik untuk menyelesaikan pembuatan kebijakan penempatan rapat.

    • Jika tidak, pilih kebijakan penempatan yang ringkas yang ada.

  10. Di bagian Hapus otomatis, Anda dapat mengaktifkan opsi hapus otomatis agar Compute Engine menghapus pemesanan secara otomatis pada tanggal dan waktu tertentu. Menghapus reservasi secara otomatis dapat berguna untuk menghindari biaya yang tidak perlu saat Anda berhenti menggunakan reservasi.

  11. Untuk membuat pemesanan, klik Buat.

    Halaman Reservations akan terbuka. Mungkin perlu waktu hingga satu menit untuk menyelesaikan pembuatan reservasi.

Menentukan properti secara langsung

Untuk membuat pemesanan satu project dengan menentukan properti secara langsung, pilih salah satu opsi berikut:

Konsol

  1. Di konsol Google Cloud , buka halaman Reservations.

    Buka Pemesanan

  2. Di tab Reservasi sesuai permintaan (default), klik Buat reservasi.

    Halaman Create a reservation akan terbuka.

  3. Untuk Name, masukkan nama untuk reservasi Anda.

  4. Untuk Region dan Zone, pilih tempat Anda ingin memesan resource.

  5. Di bagian Jenis berbagi, klik Lokal jika belum dipilih.

  6. Opsional: Untuk mengizinkan penggunaan reservasi VM GPU oleh tugas pelatihan kustom atau tugas prediksi di Vertex AI, di bagian Layanan Google Cloud, pilih Bagikan reservasi.

  7. Di bagian Gunakan dengan instance VM, pilih salah satu opsi berikut:

    • Untuk mengizinkan VM yang cocok menggunakan pemesanan ini secara otomatis, pilih Gunakan pemesanan secara otomatis jika belum dipilih.

    • Untuk menggunakan resource pemesanan ini hanya saat membuat VM yang sama persis yang secara khusus menargetkan pemesanan ini berdasarkan nama, pilih Pilih pemesanan tertentu.

  8. Untuk Number of VM instances, masukkan jumlah VM yang ingin Anda pesan.

  9. Di bagian Konfigurasi mesin, pilih Tentukan jenis mesin, lalu tentukan hal berikut:

    1. Untuk Machine family, Series, dan Machine type, pilih kelompok mesin, seri, dan jenis mesin.

    2. Opsional: Untuk menentukan platform CPU minimum atau melampirkan GPU ke VM N1, lakukan hal berikut:

      1. Untuk meluaskan bagian CPU Platform and GPU, klik peluas .

      2. Opsional: Untuk menentukan platform CPU minimum, pilih salah satu opsi untuk CPU Platform.

      3. Opsional: Untuk memasang GPU ke VM N1, klik Tambahkan GPU. Kemudian, untuk GPU type dan Number of GPUs, pilih jenis dan jumlah GPU yang akan dilampirkan ke setiap VM N1.

  10. Opsional: Untuk memasang disk SSD Lokal ke jenis mesin yang tidak menyertakan disk SSD Lokal secara default, lakukan langkah berikut:

    1. Untuk Number of disks, pilih jumlah disk SSD Lokal yang akan dilampirkan.

    2. Untuk Jenis antarmuka, pilih antarmuka disk untuk disk SSD Lokal.

  11. Opsional: Untuk menentukan kebijakan penempatan ringkas untuk reservasi yang memenuhi persyaratan, di bagian Kebijakan penempatan grup, klik daftar Pilih atau buat kebijakan penempatan grup, lalu lakukan salah satu tindakan berikut:

    • Untuk membuat kebijakan penempatan rapat yang akan ditentukan dalam pemesanan ini, lakukan hal berikut:

      1. Klik Create group placement policy.

        Panel Buat kebijakan penempatan grup akan muncul.

      2. Untuk Nama kebijakan, masukkan nama kebijakan Anda.

      3. Klik Buat.

        Mungkin perlu waktu beberapa detik untuk membuat kebijakan penempatan rapat.

    • Jika tidak, pilih kebijakan penempatan yang ringkas yang ada.

  12. Di bagian Hapus otomatis, Anda dapat mengaktifkan opsi hapus otomatis agar Compute Engine otomatis menghapus pemesanan pada tanggal dan waktu tertentu. Menghapus reservasi secara otomatis dapat berguna untuk menghindari biaya yang tidak perlu saat Anda berhenti menggunakan reservasi.

  13. Untuk membuat pemesanan, klik Buat.

    Halaman Reservations akan terbuka. Pembuatan pemesanan satu project dapat memakan waktu hingga satu menit.

gcloud

Untuk membuat reservasi satu project, gunakan perintah gcloud compute reservations create.

Untuk membuat pemesanan satu project dengan menentukan properti secara langsung dan tanpa menyertakan flag opsional, jalankan perintah berikut:

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

Ganti kode berikut:

  • RESERVATION_NAME: nama pemesanan yang akan dibuat.

  • MACHINE_TYPE: jenis mesin yang akan digunakan untuk setiap VM. Jika Anda menentukan jenis mesin A3 Mega, A3 High, atau A3 Edge, Anda harus menyertakan flag --require-specific-reservation. Hal ini menunjukkan bahwa hanya VM yang secara khusus menargetkan reservasi yang dapat menggunakannya. Untuk mengetahui informasi selengkapnya, lihat Menggunakan VM dari reservasi tertentu.

  • NUMBER_OF_VMS: jumlah VM yang akan dipesan.

  • ZONE: zona tempat memesan resource.

Misalnya, untuk membuat reservasi di zona us-central1-a untuk sepuluh VM yang masing-masing menggunakan jenis mesin N2 yang telah ditetapkan dengan 4 vCPU, jalankan perintah berikut:

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

Secara opsional, Anda dapat melakukan satu atau beberapa hal berikut:

  • Untuk memasang GPU ke VM N1 yang dipesan, sertakan tanda --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
    

    Ganti kode berikut:

    • NUMBER_OF_ACCELERATORS: jumlah GPU yang akan ditambahkan per VM yang dipesan.

    • ACCELERATOR_TYPE: model GPU yang didukung untuk VM N1. Pastikan model GPU yang Anda pilih tersedia di zona tempat Anda ingin memesan resource. Jika tidak, pembuatan pemesanan akan gagal.

  • Untuk memasang disk SSD Lokal ke jenis mesin yang tidak menyertakan disk SSD Lokal secara default, sertakan tanda --local-ssd. Anda hanya dapat melampirkan disk SSD Lokal berukuran 375 GB.

    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
    

    Ganti kode berikut:

    • NUMBER_OF_LOCAL_SSD_DISKS: jumlah disk SSD Lokal yang akan dipasang.

    • INTERFACE_TYPE: jenis antarmuka disk yang Anda inginkan untuk digunakan setiap disk SSD Lokal dan yang didukung oleh jenis mesin yang Anda tentukan. Tentukan salah satu nilai berikut:

      • Untuk antarmuka disk NVME: nvme

      • Untuk antarmuka disk SCSI: scsi

  • Agar VM yang dipesan menggunakan platform CPU minimum tertentu, bukan platform CPU default zona, sertakan flag --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
    

    Ganti MIN_CPU_PLATFORM dengan platform CPU minimum. Untuk memastikan bahwa platform CPU tersedia di zona tempat Anda memesan resource, lihat platform CPU yang tersedia menurut zona.

  • Untuk menentukan bahwa hanya VM yang secara khusus menargetkan reservasi ini yang dapat menggunakannya, sertakan flag --require-specific-reservation.

    gcloud compute reservations create RESERVATION_NAME \
        --machine-type=MACHINE_TYPE \
        --require-specific-reservation \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    
  • Untuk menentukan kebijakan penempatan rapat guna menurunkan latensi jaringan di antara VM, sertakan flag --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
    

    Ganti COMPACT_PLACEMENT_POLICY_NAME dengan nama kebijakan penempatan ringkas yang ada. Selain itu, untuk menghindari error saat membuat pemesanan satu project yang menentukan kebijakan penempatan rapat, pastikan untuk menentukan hal berikut:

    • Jenis mesin yang didukung dan jumlah maksimum VM untuk kebijakan penempatan rapat.

    • Zona dalam region tempat kebijakan penempatan rapat berada.

    • Flag --require-specific-reservation. Hal ini menunjukkan bahwa hanya VM yang secara khusus menargetkan reservasi yang dapat menggunakannya.

  • Untuk mengizinkan pemesanan VM GPU digunakan oleh tugas pelatihan kustom atau tugas prediksi di Vertex AI, sertakan flag --reservation-sharing-policy yang ditetapkan ke ALLOW_ALL.

    gcloud compute reservations create RESERVATION_NAME \
        --machine-type=MACHINE_TYPE \
        --reservation-sharing-policy=ALLOW_ALL \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    
  • Agar Compute Engine dapat menghapus pemesanan secara otomatis, pilih salah satu metode berikut:

    • Untuk menghapus reservasi pada tanggal dan waktu tertentu, gunakan perintah gcloud beta compute reservations create dengan flag --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
      

      Ganti DELETE_AT_TIME dengan tanggal dan waktu yang diformat sebagai stempel waktu RFC 3339, yang harus seperti berikut:

      YYYY-MM-DDTHH:MM:SSOFFSET
      

      Ganti kode berikut:

      • YYYY-MM-DD: tanggal yang diformat sebagai tahun 4 digit, bulan 2 digit, dan hari 2 digit dalam bulan, yang dipisahkan oleh tanda hubung (-).

      • HH:MM:SS: waktu yang diformat sebagai jam 2 digit menggunakan waktu 24 jam, menit 2 digit, dan detik 2 digit, yang dipisahkan oleh titik dua (:).

      • OFFSET: zona waktu yang diformat sebagai offset dari Waktu Universal Terkoordinasi (UTC). Misalnya, untuk menggunakan Waktu Standar Pasifik (PST), tentukan -08:00. Atau, untuk tidak menggunakan penyeimbang, tentukan Z.

    • Untuk menghapus pemesanan setelah durasi tertentu, gunakan perintah gcloud beta compute reservations create dengan flag --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
      

      Ganti DELETE_AFTER_DURATION dengan durasi dalam hari, jam, menit, atau detik. Misalnya, tentukan 30m selama 30 menit, atau 1d2h3m4s untuk 1 hari, 2 jam, 3 menit, dan 4 detik.

Go

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

Untuk membuat pemesanan satu project, gunakan resource Terraform google_compute_reservation.

Misalnya, untuk membuat pemesanan satu project untuk satu jenis mesin N2 yang telah ditentukan sebelumnya dengan 2 vCPU, gunakan resource berikut:


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
}

Untuk mengetahui informasi selengkapnya tentang cara menggunakan Terraform, lihat artikel Menggunakan Terraform dengan Google Cloud.

REST

Untuk membuat pemesanan satu project, buat permintaan POST ke metode reservations.insert.

Untuk membuat pemesanan satu project dengan menentukan properti secara langsung dan tanpa menyertakan kolom opsional apa pun, buat permintaan POST berikut:

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"
    }
  }
}

Ganti kode berikut:

  • PROJECT_ID: ID project tempat Anda ingin memesan resource.

  • ZONE: zona tempat memesan resource.

  • RESERVATION_NAME: nama pemesanan yang akan dibuat.

  • NUMBER_OF_VMS: jumlah VM yang akan dipesan.

  • MACHINE_TYPE: jenis mesin yang akan digunakan untuk setiap VM. Jika Anda menentukan jenis mesin A3 Mega, A3 High, atau A3 Edge, Anda harus menyertakan kolom specificReservationRequired di isi permintaan, dan menetapkan kolom ke true. Hal ini menunjukkan bahwa hanya VM yang secara khusus menargetkan reservasi yang dapat menggunakannya. Untuk mengetahui informasi selengkapnya, lihat Menggunakan VM dari reservasi tertentu.

Misalnya, untuk membuat reservasi di zona us-central1-a untuk sepuluh VM yang masing-masing menggunakan jenis mesin N2 yang telah ditetapkan dengan 4 vCPU, buat permintaan POST berikut:

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",
    }
  }
}

Secara opsional, Anda dapat melakukan satu atau beberapa hal berikut:

  • Untuk memasang GPU ke VM N1 yang dipesan, sertakan kolom guestAccelerators di isi permintaan.

    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"
        }
      }
    }
    

    Ganti kode berikut:

    • NUMBER_OF_ACCELERATORS: jumlah GPU yang akan ditambahkan per VM yang dipesan.

    • ACCELERATOR_TYPE: model GPU yang didukung untuk VM N1. Pastikan model GPU yang Anda pilih tersedia di zona tempat Anda ingin memesan resource. Jika tidak, pembuatan pemesanan akan gagal.

  • Untuk memasang disk SSD Lokal ke jenis mesin yang tidak menyertakan disk SSD Lokal secara default, sertakan kolom localSsds dalam isi permintaan. Anda hanya dapat memasang disk SSD Lokal berukuran 375 GB.

    Misalnya, untuk memasang dua disk SSD Lokal ke jenis mesin yang ingin Anda pesan, buat permintaan sebagai berikut:

    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"
        }
      }
    }
    

    Ganti INTERFACE_TYPE dengan jenis antarmuka disk yang Anda inginkan untuk digunakan setiap disk SSD Lokal dan yang didukung oleh jenis mesin yang Anda tentukan. Tentukan salah satu nilai berikut:

    • Untuk antarmuka disk NVME: NVME

    • Untuk antarmuka disk SCSI: SCSI

  • Agar VM yang dipesan menggunakan platform CPU minimum tertentu dan bukan platform CPU default zona, sertakan kolom minCpuPlatform dalam isi permintaan.

    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"
        }
      }
    }
    

    Ganti MIN_CPU_PLATFORM dengan platform CPU minimum. Untuk memastikan bahwa platform CPU tersedia di zona tempat Anda memesan resource, lihat platform CPU yang tersedia menurut zona.

  • Untuk menentukan kebijakan penempatan rapat guna mengurangi latensi jaringan di antara VM yang dipesan, sertakan kolom resourcePolicies dalam isi permintaan.

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

    Ganti kode berikut:

    • REGION: region tempat kebijakan penempatan yang ringkas berada. Anda hanya dapat membuat reservasi dalam region kebijakan penempatan.

    • COMPACT_PLACEMENT_POLICY_NAME: nama kebijakan penempatan ringkas yang ada.

    Selain itu, untuk menghindari error saat membuat pemesanan satu project yang menentukan kebijakan penempatan rapat, pastikan untuk menentukan berikut ini:

    • Jenis mesin yang didukung untuk kebijakan penempatan rapat.

    • Kolom specificReservationRequired ditetapkan ke true. Hal ini menunjukkan bahwa hanya VM yang secara khusus menargetkan reservasi ini yang dapat menggunakannya.

  • Untuk menentukan bahwa hanya VM yang secara khusus menargetkan pemesanan ini yang dapat menggunakannya, sertakan kolom specificReservationRequired dalam isi permintaan dan tetapkan kolom ke 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
    }
    
  • Untuk mengizinkan reservasi VM GPU digunakan oleh tugas pelatihan kustom atau tugas prediksi di Vertex AI, sertakan kolom serviceShareType dan tetapkan ke 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"
        }
      }
    }
    
  • Agar Compute Engine dapat menghapus pemesanan secara otomatis, pilih salah satu metode berikut:

    • Untuk menghapus pemesanan pada tanggal dan waktu tertentu, buat permintaan POST ke metode beta.reservations.insert. Dalam isi permintaan, sertakan kolom 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"
          }
        }
      }
      

      Ganti DELETE_AT_TIME dengan tanggal dan waktu yang diformat sebagai stempel waktu RFC 3339, yang harus seperti berikut:

      YYYY-MM-DDTHH:MM:SSOFFSET
      

      Ganti kode berikut:

      • YYYY-MM-DD: tanggal yang diformat sebagai tahun 4 digit, bulan 2 digit, dan hari 2 digit dalam bulan, yang dipisahkan oleh tanda hubung (-).

      • HH:MM:SS: waktu yang diformat sebagai jam 2 digit menggunakan waktu 24 jam, menit 2 digit, dan detik 2 digit, yang dipisahkan oleh titik dua (:).

      • OFFSET: zona waktu yang diformat sebagai offset dari Waktu Universal Terkoordinasi (UTC). Misalnya, untuk menggunakan Waktu Standar Pasifik (PST), tentukan -08:00. Atau, untuk tidak menggunakan penyeimbang, tentukan Z.

    • Untuk menghapus pemesanan setelah durasi tertentu, buat permintaan POST ke metode beta.reservations.insert. Dalam isi permintaan, sertakan kolom 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"
          }
        }
      }
      

      Ganti DELETE_AFTER_DURATION dengan durasi dalam detik. Misalnya, tentukan 86400 untuk 86.400 detik (1 hari).

Pemecahan masalah

Pelajari cara memecahkan masalah pembuatan reservasi.

Langkah berikutnya