Menggunakan pemesanan


Dokumen ini menjelaskan cara menggunakan reservasi di Compute Engine. Untuk mempelajari cara menggunakan reservasi di produk Google Cloud lainnya, lihat dokumentasi berikut:

Setelah Anda membuat pemesanan, atau Compute Engine otomatis membuat pemesanan untuk Anda guna memenuhi pemesanan untuk masa mendatang, Compute Engine akan menyimpan resource yang Anda pesan untuk Anda. Kemudian, Anda dapat menggunakan resource yang dipesan tersebut untuk membuat instance Compute Engine yang cocok dengan properti pemesanan. Tindakan ini dikenal sebagai menggunakan reservasi. Anda dapat menggunakan kapasitas yang direservasi untuk membuat instance hingga pemesanan digunakan sepenuhnya.

Batasan

Anda tidak dapat menggunakan reservasi untuk membuat resource Compute Engine berikut:

  • Spot VM atau instance preemptible

  • Sole-tenant node

Sebelum memulai

  • Jika Anda belum melakukannya, siapkan autentikasi. Autentikasi adalah proses yang digunakan untuk memverifikasi identitas Anda agar dapat mengakses Google Cloud layanan dan API. Untuk menjalankan kode atau contoh dari lingkungan pengembangan lokal, Anda dapat mengautentikasi 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. Go

      Untuk menggunakan contoh Go 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.

      Java

      Untuk menggunakan contoh Java 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.

      Node.js

      Untuk menggunakan contoh Node.js 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.

      Python

      Untuk menggunakan contoh Python 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 informasi selengkapnya, lihat Mengautentikasi untuk menggunakan REST dalam Google Cloud dokumentasi autentikasi.

Peran yang diperlukan

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

Peran yang telah ditentukan ini berisi izin yang diperlukan untuk menggunakan reservasi. Untuk melihat izin yang benar-benar diperlukan, luaskan bagian Izin yang diperlukan:

Izin yang diperlukan

Izin berikut diperlukan untuk menggunakan reservasi:

  • Untuk membuat pemesanan: compute.reservations.create pada project
  • Untuk membuat instance:
    • compute.instances.create pada project
    • Untuk menggunakan image kustom guna membuat VM: compute.images.useReadOnly pada image
    • Untuk menggunakan snapshot guna membuat VM: compute.snapshots.useReadOnly pada snapshot
    • Untuk menggunakan template instance guna membuat VM: compute.instanceTemplates.useReadOnly di template instance
    • Untuk menetapkan jaringan lama ke VM: compute.networks.use di project
    • Untuk menentukan alamat IP statis untuk VM: compute.addresses.use pada project
    • Untuk menetapkan alamat IP eksternal ke VM saat menggunakan jaringan lama: compute.networks.useExternalIp di project
    • Untuk menentukan subnet bagi VM: compute.subnetworks.use di project atau di subnet yang dipilih
    • Untuk menetapkan alamat IP eksternal ke VM saat menggunakan jaringan VPC: compute.subnetworks.useExternalIp di project atau di subnet yang dipilih
    • Untuk menetapkan metadata instance VM untuk VM: compute.instances.setMetadata pada project
    • Untuk menetapkan tag untuk VM: compute.instances.setTags di VM
    • Untuk menetapkan label untuk VM: compute.instances.setLabels di VM
    • Untuk menetapkan akun layanan yang akan digunakan VM: compute.instances.setServiceAccount di VM
    • Untuk membuat disk baru bagi VM: compute.disks.create pada project
    • Untuk memasang disk yang ada dalam mode hanya baca atau baca-tulis: compute.disks.use pada disk
    • Untuk memasang disk yang ada dalam mode hanya baca: compute.disks.useReadOnly pada disk
  • Untuk membuat template instance: compute.instanceTemplates.create pada project

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

Menggunakan reservasi

Contoh di bagian berikut menunjukkan cara menggunakan reservasi dengan membuat satu instance komputasi. Anda juga dapat menggunakan reservasi dengan membuat instance yang cocok dengan properti reservasi menggunakan opsi deployment yang berbeda, atau dengan memperbarui properti instance yang ada agar cocok dengan pemesanan yang digunakan secara otomatis.

Untuk menggunakan reservasi, gunakan salah satu metode berikut:

Menggunakan reservasi yang digunakan secara otomatis

Saat Anda membuat reservasi yang digunakan secara otomatis, instance komputasi yang cocok dengan properti reservasi akan otomatis menggunakannya. Perilaku konsumsi ini berlaku untuk instance baru dan yang sudah ada dan berjalan. Saat Anda membuat pemesanan, atau Compute Engine otomatis membuat pemesanan untuk memenuhi pemesanan untuk masa mendatang, jenis pemesanan ini adalah setelan default.

Jika properti pemesanan otomatis satu project dan pemesanan otomatis bersama cocok, instance dalam project Anda akan menggunakan pemesanan satu project terlebih dahulu, lalu menggunakan pemesanan bersama. Untuk informasi selengkapnya, lihat urutan penggunaan untuk reservasi.

Untuk membuat dan menggunakan contoh reservasi otomatis, pilih salah satu opsi berikut:

Konsol

Contoh berikut menunjukkan cara membuat reservasi otomatis di zona us-central1-a untuk tiga instance N2 dengan 32 vCPU, dan Intel Cascade Lake sebagai platform CPU minimum. Contoh ini juga menunjukkan cara membuat satu instance untuk menggunakan reservasi.

Untuk membuat contoh reservasi otomatis dan menggunakannya, lakukan hal berikut:

  1. Untuk membuat contoh reservasi, selesaikan langkah-langkah berikut:

    1. Di konsol Google Cloud, buka halaman Reservations.

      Buka Pemesanan

    2. Di tab Pemesanan on-demand (default), klik Buat pemesanan. Halaman Buat pemesanan akan muncul.

    3. Di kolom Nama, masukkan nama untuk pemesanan. Misalnya, masukkan reservation-01.

    4. Pilih Region dan Zone tempat Anda ingin memesan resource. Misalnya, pilih us-central1 dan us-central1-a.

    5. Di bagian Share type, lakukan salah satu hal berikut:

      • Untuk membuat pemesanan satu project, pilih Lokal.

      • Untuk membuat pemesanan bersama, pilih Shared, lalu tentukan project yang ingin Anda gunakan dalam pemesanan bersama.

    6. Di bagian Use with VM instance, pilih Use reservation automatically, jika belum dipilih.

    7. Di kolom Number of VM instances, masukkan 3.

    8. Di tab General purpose, pilih N2.

    9. Di bagian Machine type, pada tab Preset (default), pilih n2-standard-32.

    10. Luaskan CPU platform and GPU, lalu, di kolom CPU platform, pilih Intel Cascade Lake or later.

    11. Klik Buat.

  2. Untuk membuat instance yang menggunakan contoh reservasi, selesaikan langkah-langkah berikut:

    1. Di konsol Google Cloud, buka halaman Create an instance.

      Buka halaman Buat instance

      Halaman Create an instance akan muncul dan menampilkan panel Machine configuration.

    2. Di panel Machine configuration, lakukan hal berikut:

      1. Di kolom Name, masukkan nama untuk instance. Untuk contoh ini, masukkan instance-01.

      2. Tentukan Region dan Zone tempat Anda ingin memesan resource. Untuk contoh ini, pilih us-central1 dan us-central1-a.

      3. Di tab General purpose, pilih N2.

      4. Di bagian Machine type, pada tab Preset (default), pilih n2-standard-32.

      5. Luaskan bagian Advanced options, lalu, di kolom CPU platform, pilih Intel Cascade Lake atau yang lebih baru.

    3. Di menu navigasi, klik Lanjutan.

    4. Di bagian Reservations pada panel Advanced, pilih Use automatic selection, jika belum dipilih.

    5. Klik Buat.

gcloud

Contoh berikut menunjukkan cara membuat reservasi otomatis di zona us-central1-a untuk tiga instance N2 dengan 32 vCPU, dan Intel Cascade Lake sebagai platform CPU minimum. Contoh ini juga menunjukkan cara membuat satu instance untuk menggunakan reservasi.

Untuk membuat contoh reservasi otomatis dan menggunakannya, lakukan hal berikut:

  1. Untuk membuat contoh reservasi, gunakan perintah gcloud compute reservations create:

    gcloud compute reservations create reservation-01 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --vm-count=3 \
        --zone=us-central1-a
    
  2. Untuk membuat instance yang menggunakan contoh reservasi, gunakan perintah gcloud compute instances create dengan flag --reservation-affinity yang ditetapkan ke any. Karena any adalah konfigurasi default, Anda juga dapat menghapus tanda ini.

    gcloud compute instances create instance-01 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --reservation-affinity=any \
        --zone=us-central1-a
    

Go

Untuk membuat contoh pemesanan otomatis menggunakan template instance, dan membuat instance untuk menggunakan pemesanan menggunakan template yang sama, gunakan contoh kode berikut:

import (
	"context"
	"fmt"
	"io"

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

// consumeAnyReservation creates instance, consuming any available reservation
func consumeAnyReservation(w io.Writer, projectID, zone, instanceName, sourceTemplate string) error {
	// projectID := "your_project_id"
	// zone := "us-west3-a"
	// instanceName := "your_instance_name"
	// sourceTemplate: existing template path. Following formats are allowed:
	//  	- projects/{project_id}/global/instanceTemplates/{template_name}
	//  	- projects/{project_id}/regions/{region}/instanceTemplates/{template_name}
	//  	- https://www.googleapis.com/compute/v1/projects/{project_id}/global/instanceTemplates/instanceTemplate
	//  	- https://www.googleapis.com/compute/v1/projects/{project_id}/regions/{region}/instanceTemplates/instanceTemplate

	ctx := context.Background()

	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

	req := &computepb.InsertInstanceRequest{
		Project:                projectID,
		Zone:                   zone,
		SourceInstanceTemplate: proto.String(sourceTemplate),
		InstanceResource: &computepb.Instance{
			Name: proto.String(instanceName),
			// specifies that any matching reservation should be consumed
			ReservationAffinity: &computepb.ReservationAffinity{
				ConsumeReservationType: proto.String("ANY_RESERVATION"),
			},
		},
	}

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

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

	return nil
}

Java

Contoh berikut menunjukkan cara membuat instance N1 dengan empat vCPU, dan Intel Skylake sebagai platform CPU minimum di zona us-central1-a. Instance otomatis menggunakan reservasi yang cocok.

Untuk membuat instance contoh, gunakan contoh kode berikut:

import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.ANY_RESERVATION;

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.InsertInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.ReservationAffinity;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ConsumeAnyMatchingReservation {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Zone where the VM instance will be created.
    String zone = "us-central1-a";
    // Name of the VM instance you want to query.
    String instanceName = "YOUR_INSTANCE_NAME";
    // machineType: machine type of the VM being created.
    // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
    String machineTypeName = "n1-standard-4";
    // sourceImage: path to the operating system image to mount.
    // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
    String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
    // diskSizeGb: storage size of the boot disk to attach to the instance.
    long diskSizeGb = 10L;
    // networkName: network interface to associate with the instance.
    String networkName = "default";
    // Minimum CPU platform of the instances.
    String minCpuPlatform = "Intel Skylake";

    createInstanceAsync(projectId, zone, instanceName, machineTypeName, sourceImage,
        diskSizeGb, networkName, minCpuPlatform);
  }

  // Create a virtual machine targeted with the reserveAffinity field.
  // In this consumption model, existing and new VMs automatically consume a reservation
  // if their properties match the VM properties specified in the reservation.
  public static Instance createInstanceAsync(String projectId, String zone,
      String instanceName, String machineTypeName, String sourceImage,
      long diskSizeGb, String networkName, String minCpuPlatform)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    String machineType = String.format("zones/%s/machineTypes/%s", zone, machineTypeName);
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (InstancesClient instancesClient = InstancesClient.create()) {
      AttachedDisk disk =
          AttachedDisk.newBuilder()
              .setBoot(true)
              .setAutoDelete(true)
              .setType(AttachedDisk.Type.PERSISTENT.toString())
              .setDeviceName("disk-1")
              .setInitializeParams(
                  AttachedDiskInitializeParams.newBuilder()
                      .setSourceImage(sourceImage)
                      .setDiskSizeGb(diskSizeGb)
                      .build())
              .build();

      NetworkInterface networkInterface = NetworkInterface.newBuilder()
          .setName(networkName)
          .build();

      ReservationAffinity reservationAffinity =
          ReservationAffinity.newBuilder()
              .setConsumeReservationType(ANY_RESERVATION.toString())
              .build();

      Instance instanceResource =
          Instance.newBuilder()
              .setName(instanceName)
              .setMachineType(machineType)
              .addDisks(disk)
              .addNetworkInterfaces(networkInterface)
              .setMinCpuPlatform(minCpuPlatform)
              .setReservationAffinity(reservationAffinity)
              .build();

      InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setInstanceResource(instanceResource)
          .build();

      OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
          insertInstanceRequest);

      Operation response = operation.get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        return null;
      }
      return instancesClient.get(projectId, zone, instanceName);
    }
  }
}

Node.js

Contoh berikut menunjukkan cara membuat instance N1 dengan empat vCPU, dan Intel Skylake sebagai platform CPU minimum di zona us-central1-a. Instance otomatis menggunakan reservasi yang cocok.

Untuk membuat instance contoh, gunakan contoh kode berikut:

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

// Instantiate a reservationsClient
const instancesClient = new computeLib.InstancesClient();
// Instantiate a zoneOperationsClient
const zoneOperationsClient = new computeLib.ZoneOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The ID of the project where you want to create instance.
const projectId = await instancesClient.getProjectId();
// The zone in which to create instance.
const zone = 'us-central1-a';
// The name of the instance to create.
// const instanceName = 'instance-01';
// Machine type to use for VM.
const machineType = 'n1-standard-4';

// Create instance to consume reservation if their properties match the VM properties
async function callCreateInstanceToConsumeAnyReservation() {
  // Describe the size and source image of the boot disk to attach to the instance.
  const disk = new compute.Disk({
    boot: true,
    autoDelete: true,
    type: 'PERSISTENT',
    initializeParams: {
      diskSizeGb: '10',
      sourceImage: 'projects/debian-cloud/global/images/family/debian-12',
    },
  });

  //  Define networkInterface
  const networkInterface = new compute.NetworkInterface({
    name: 'global/networks/default',
  });

  // Define reservationAffinity
  const reservationAffinity = new compute.ReservationAffinity({
    consumeReservationType: 'ANY_RESERVATION',
  });

  // Create an instance
  const instance = new compute.Instance({
    name: instanceName,
    machineType: `zones/${zone}/machineTypes/${machineType}`,
    minCpuPlatform: 'Intel Skylake',
    disks: [disk],
    networkInterfaces: [networkInterface],
    reservationAffinity,
  });

  const [response] = await instancesClient.insert({
    project: projectId,
    instanceResource: instance,
    zone,
  });

  let operation = response.latestResponse;

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

  console.log(`Instance ${instanceName} created.`);
}

await callCreateInstanceToConsumeAnyReservation();

Python

Contoh berikut menunjukkan cara membuat reservasi otomatis di zona us-central1-a untuk tiga instance N1 dengan satu vCPU, dan Intel Ivy sebagai platform CPU minimum. Contoh ini juga menunjukkan cara membuat satu instance untuk menggunakan reservasi.

Untuk membuat contoh reservasi otomatis dan menggunakannya, lakukan hal berikut:

from __future__ import annotations

import sys
from typing import Any

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


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

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

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

    Returns:
        Whatever the operation.result() returns.

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

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

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

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

    return result


def consume_any_project_reservation(
    project_id: str,
    zone: str,
    reservation_name: str,
    instance_name: str,
    machine_type: str = "n1-standard-1",
    min_cpu_platform: str = "Intel Ivy Bridge",
) -> compute_v1.Instance:
    """
    Creates a specific reservation in a single project and launches a VM
    that consumes the newly created reservation.
    Args:
        project_id (str): The ID of the Google Cloud project.
        zone (str): The zone to create the reservation.
        reservation_name (str): The name of the reservation to create.
        instance_name (str): The name of the instance to create.
        machine_type (str): The machine type for the instance.
        min_cpu_platform (str): The minimum CPU platform for the instance.
    """
    instance_properties = (
        compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
            machine_type=machine_type,
            min_cpu_platform=min_cpu_platform,
        )
    )

    reservation = compute_v1.Reservation(
        name=reservation_name,
        specific_reservation=compute_v1.AllocationSpecificSKUReservation(
            count=3,
            instance_properties=instance_properties,
        ),
    )

    # Create a reservation client
    client = compute_v1.ReservationsClient()
    operation = client.insert(
        project=project_id,
        zone=zone,
        reservation_resource=reservation,
    )
    wait_for_extended_operation(operation, "Reservation creation")

    instance = compute_v1.Instance()
    instance.name = instance_name
    instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
    instance.min_cpu_platform = min_cpu_platform
    instance.zone = zone

    # Set the reservation affinity to target any matching reservation
    instance.reservation_affinity = compute_v1.ReservationAffinity(
        consume_reservation_type="ANY_RESERVATION",  # Type of reservation to consume
    )
    # Define the disks for the instance
    instance.disks = [
        compute_v1.AttachedDisk(
            boot=True,  # Indicates that this is a boot disk
            auto_delete=True,  # The disk will be deleted when the instance is deleted
            initialize_params=compute_v1.AttachedDiskInitializeParams(
                source_image="projects/debian-cloud/global/images/family/debian-11",
                disk_size_gb=10,
            ),
        )
    ]
    instance.network_interfaces = [
        compute_v1.NetworkInterface(
            network="global/networks/default",  # The network to use
            access_configs=[
                compute_v1.AccessConfig(
                    name="External NAT",  # Name of the access configuration
                    type="ONE_TO_ONE_NAT",  # Type of access configuration
                )
            ],
        )
    ]
    # Create a request to insert the instance
    request = compute_v1.InsertInstanceRequest()
    request.zone = zone
    request.project = project_id
    request.instance_resource = instance

    vm_client = compute_v1.InstancesClient()
    operation = vm_client.insert(request)
    wait_for_extended_operation(operation, "instance creation")
    print(f"Instance {instance_name} that targets any open reservation created.")

    return vm_client.get(project=project_id, zone=zone, instance=instance_name)

REST

Contoh berikut menunjukkan cara membuat reservasi otomatis di zona us-central1-a untuk tiga instance N2 dengan 32 vCPU, dan Intel Cascade Lake sebagai platform CPU minimum. Contoh ini juga menunjukkan cara membuat satu instance untuk menggunakan reservasi.

Untuk membuat contoh reservasi otomatis dan menggunakannya, lakukan hal berikut:

  1. Untuk membuat contoh pemesanan, buat permintaan POST ke metode reservations.insert:

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations
    
    {
      "name": "reservation-01",
      "specificReservation": {
        "count": "3",
        "instanceProperties": {
          "machineType": "n2-standard-32",
          "minCpuPlatform": "Intel Cascade Lake",
        }
      }
    }
    
  2. Untuk membuat instance yang menggunakan contoh pemesanan, buat permintaan POST ke metode instances.insert. Dalam isi permintaan, sertakan kolom consumeReservationType yang ditetapkan ke ANY_RESERVATION. Namun, karena ANY_RESERVATION adalah konfigurasi default, Anda juga dapat menghapus kolom tersebut.

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/instances
    
    {
      "name": "instance-01",
      "machineType": "zones/us-central1-a/machineTypes/n2-standard-32",
      "minCpuPlatform": "Intel Cascade Lake",
      "disks": [
        {
          "boot": true,
          "initializeParams": {
            "sourceImage": "projects/debian-cloud/global/images/family/debian-12"
          }
        }
      ],
      "networkInterfaces": [
        {
          "network": "global/networks/default"
        }
      ],
      "reservationAffinity": {
        "consumeReservationType": "ANY_RESERVATION"
      }
    }
    

Menggunakan reservasi yang ditargetkan secara khusus

Pemesanan yang ditargetkan secara khusus memungkinkan instance komputasi baru menggunakan pemesanan yang cocok hanya jika instance menargetkan pemesanan. Instance hanya berhasil dibuat jika propertinya cocok dengan properti reservasi. Jika tidak, Anda akan mengalami error.

Berdasarkan metode pembuatan yang ingin Anda gunakan, buat reservasi dan instance tertentu yang menargetkannya sebagai berikut:

Metode pembuatan Saat Anda membuat reservasi Saat Anda membuat instance
Konsol Google Cloud Di bagian Use with VM instance, pilih Select specific reservation. Di panel Advanced, di bagian Reservations, pilih Choose a reservation.
Google Cloud CLI Sertakan flag --require-specific-reservation. Sertakan flag berikut:
  • Flag --reservation-affinity ditetapkan ke specific.
  • Flag --reservation ditetapkan ke URL reservasi.
Go Sertakan kolom SpecificReservationRequired yang ditetapkan ke true. Di kolom ReservationAffinity, sertakan kolom berikut:
  • Kolom ConsumeReservationType ditetapkan ke SPECIFIC_RESERVATION.
  • Kolom Key ditetapkan ke compute.googleapis.com/reservation-name.
  • Kolom Values ditetapkan ke URL reservasi.
Java Sertakan kolom setSpecificReservationRequired yang ditetapkan ke true. Di kolom ReservationAffinity, sertakan kolom berikut:
  • Kolom setConsumeReservationType ditetapkan ke SPECIFIC_RESERVATION.
  • Kolom setKey ditetapkan ke compute.googleapis.com/reservation-name.
  • Kolom addValues ditetapkan ke URL reservasi.
Node.js dan REST API Sertakan kolom specificReservationRequired yang ditetapkan ke true. Di kolom reservationAffinity, sertakan kolom berikut:
  • Kolom consumeReservationType ditetapkan ke SPECIFIC_RESERVATION.
  • Kolom key ditetapkan ke compute.googleapis.com/reservation-name.
  • Kolom values ditetapkan ke URL reservasi.
Python dan Terraform Sertakan kolom specific_reservation_required yang ditetapkan ke true. Di kolom reservation_affinity, sertakan kolom berikut:
  • Kolom consume_reservation_type ditetapkan ke SPECIFIC_RESERVATION.
  • Kolom key ditetapkan ke compute.googleapis.com/reservation-name.
  • Kolom values ditetapkan ke URL reservasi.

Untuk membuat contoh reservasi khusus dan instance untuk menggunakannya, pilih salah satu opsi berikut:

Konsol

Contoh berikut menunjukkan cara membuat reservasi tertentu di zona us-central1-a untuk tiga instance N2 dengan 32 vCPU, dan Intel Cascade Lake sebagai platform CPU minimum. Contoh ini juga menunjukkan cara membuat satu instance untuk menggunakan reservasi.

Untuk membuat contoh reservasi khusus dan menggunakannya, lakukan hal berikut:

  1. Untuk membuat contoh reservasi, selesaikan langkah-langkah berikut:

    1. Di konsol Google Cloud, buka halaman Reservations.

      Buka Pemesanan

    2. Di tab Pemesanan on-demand (default), klik Buat pemesanan. Halaman Buat pemesanan akan muncul.

    3. Di kolom Nama, masukkan nama untuk pemesanan. Misalnya, masukkan reservation-02.

    4. Tentukan Region dan Zona tempat Anda ingin memesan resource. Untuk contoh ini, pilih us-central1 dan us-central1-a.

    5. Di bagian Share type, lakukan salah satu hal berikut:

      • Untuk membuat pemesanan satu project, pilih Lokal.

      • Untuk membuat pemesanan bersama, pilih Shared, lalu tentukan project yang ingin Anda gunakan dalam pemesanan bersama.

    6. Di bagian Use with VM instance, pilih Select specific reservation.

    7. Di kolom Number of VM instances, masukkan 3.

    8. Di tab General purpose, pilih N2.

    9. Di bagian Machine type, pada tab Preset (default), pilih n2-standard-32.

    10. Luaskan CPU platform and GPU, lalu, di kolom CPU platform, pilih Intel Cascade Lake or later.

    11. Klik Buat.

  2. Untuk membuat instance yang menggunakan contoh reservasi, selesaikan langkah-langkah berikut:

    1. Di konsol Google Cloud, buka halaman Create an instance.

      Buka halaman Buat instance

      Halaman Create an instance akan muncul dan menampilkan panel Machine configuration.

    2. Di panel Machine configuration, lakukan hal berikut:

      1. Di kolom Name, masukkan nama untuk instance. Untuk contoh ini, masukkan instance-02.

      2. Tentukan Region dan Zona tempat Anda ingin memesan resource. Untuk contoh ini, pilih us-central1 dan us-central1-a.

      3. Di tab General purpose, pilih N2.

      4. Di bagian Machine type, pada tab Preset (default), pilih n2-standard-32.

      5. Luaskan bagian Advanced options, lalu, di kolom CPU platform, pilih Intel Cascade Lake or later.

    3. Di menu navigasi, klik Lanjutan.

    4. Di bagian Reservations pada panel Advanced, pilih Choose a reservation, lalu klik Choose reservation.

    5. Di panel Choose a reservation yang muncul, lakukan hal berikut:

      1. Pilih reservasi tertentu yang Anda buat di langkah sebelumnya. Jika Anda ingin menggunakan pemesanan bersama yang ada di project lain, dalam daftar Project, pilih project tempat pemesanan berada.

      2. Klik Pilih.

    6. Klik Buat.

gcloud

Contoh berikut menunjukkan cara membuat reservasi tertentu di zona us-central1-a untuk tiga instance N2 dengan 32 vCPU, dan Intel Cascade Lake sebagai platform CPU minimum. Contoh ini juga menunjukkan cara membuat satu instance untuk menggunakan reservasi.

Untuk membuat contoh reservasi khusus dan menggunakannya, lakukan hal berikut:

  1. Untuk membuat contoh pemesanan, gunakan perintah gcloud compute reservations create dengan flag --require-specific-reservation:

    gcloud compute reservations create reservation-02 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --require-specific-reservation \
        --vm-count=3 \
        --zone=us-central1-a
    
  2. Untuk membuat instance yang menggunakan contoh pemesanan, gunakan perintah gcloud compute instances create dengan flag --reservation dan --reservation-affinity=specific:

    gcloud compute instances create instance-02 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --reservation-affinity=specific \
        --reservation=RESERVATION_URL \
        --zone=us-central1-a
    

    Ganti RESERVATION_URL dengan URL reservasi. Tentukan salah satu nilai berikut:

    • Jika Anda membuat reservasi di project yang sama: reservation-02

    • Jika reservasi berada di project lain: projects/PROJECT_ID/reservations/reservation-02

Go

Contoh berikut menunjukkan cara membuat instance N2 dengan 32 vCPU, dan Intel Cascade Lake sebagai platform CPU minimum, di zona us-central1-a untuk menggunakan reservasi tertentu yang cocok:

  • Untuk membuat contoh instance guna menggunakan pemesanan khusus satu project, gunakan contoh kode berikut:

    import (
    	"context"
    	"fmt"
    	"io"
    
    	compute "cloud.google.com/go/compute/apiv1"
    	computepb "cloud.google.com/go/compute/apiv1/computepb"
    	"google.golang.org/protobuf/proto"
    )
    
    // consumeSpecificReservation creates instance, consuming specific reservation
    // Note: respective reservation should have SpecificReservationRequired: true
    func consumeSpecificReservation(w io.Writer, projectID, zone, instanceName, reservationName string) error {
    	// projectID := "your_project_id"
    	// zone := "us-west3-a"
    	// reservationName := "your_reservation_name"
    	// instanceName := "your_instance_name"
    
    	ctx := context.Background()
    	machineType := fmt.Sprintf("zones/%s/machineTypes/%s", zone, "n2-standard-32")
    	sourceImage := "projects/debian-cloud/global/images/family/debian-12"
    
    	instancesClient, err := compute.NewInstancesRESTClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewInstancesRESTClient: %w", err)
    	}
    	defer instancesClient.Close()
    
    	req := &computepb.InsertInstanceRequest{
    		Project: projectID,
    		Zone:    zone,
    		InstanceResource: &computepb.Instance{
    			Disks: []*computepb.AttachedDisk{
    				{
    					InitializeParams: &computepb.AttachedDiskInitializeParams{
    						DiskSizeGb:  proto.Int64(10),
    						SourceImage: proto.String(sourceImage),
    					},
    					AutoDelete: proto.Bool(true),
    					Boot:       proto.Bool(true),
    					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
    				},
    			},
    			MachineType:    proto.String(machineType),
    			MinCpuPlatform: proto.String("Intel Cascade Lake"),
    			Name:           proto.String(instanceName),
    			NetworkInterfaces: []*computepb.NetworkInterface{
    				{
    					Name: proto.String("global/networks/default"),
    				},
    			},
    			// specifies particular reservation, which should be consumed
    			ReservationAffinity: &computepb.ReservationAffinity{
    				ConsumeReservationType: proto.String("SPECIFIC_RESERVATION"),
    				Key:                    proto.String("compute.googleapis.com/reservation-name"),
    				Values:                 []string{reservationName},
    			},
    		},
    	}
    
    	op, err := instancesClient.Insert(ctx, req)
    	if err != nil {
    		return fmt.Errorf("unable to create instance: %w", err)
    	}
    
    	if err = op.Wait(ctx); err != nil {
    		return fmt.Errorf("unable to wait for the operation: %w", err)
    	}
    	fmt.Fprintf(w, "Instance created from reservation\n")
    
    	return nil
    }
    
  • Untuk membuat instance contoh guna menggunakan pemesanan bersama tertentu, gunakan contoh kode berikut:

    import (
    	"context"
    	"fmt"
    	"io"
    
    	computepb "cloud.google.com/go/compute/apiv1/computepb"
    	"google.golang.org/protobuf/proto"
    )
    
    // consumeSpecificSharedReservation consumes specific shared reservation in particular zone
    func consumeSpecificSharedReservation(w io.Writer, client InstanceClientInterface, projectID, baseProjectId, zone, instanceName, reservationName string) error {
    	// client, err := compute.NewInstancesRESTClient(ctx)
    	// projectID := "your_project_id". Project where reservation is created.
    	// baseProjectId := "shared_project_id". Project where instance will be consumed and created.
    	// zone := "us-west3-a"
    	// reservationName := "your_reservation_name"
    	// instanceName := "your_instance_name"
    
    	ctx := context.Background()
    	machineType := fmt.Sprintf("zones/%s/machineTypes/%s", zone, "n2-standard-32")
    	sourceImage := "projects/debian-cloud/global/images/family/debian-12"
    	sharedReservation := fmt.Sprintf("projects/%s/reservations/%s", baseProjectId, reservationName)
    
    	req := &computepb.InsertInstanceRequest{
    		Project: projectID,
    		Zone:    zone,
    		InstanceResource: &computepb.Instance{
    			Disks: []*computepb.AttachedDisk{
    				{
    					InitializeParams: &computepb.AttachedDiskInitializeParams{
    						DiskSizeGb:  proto.Int64(10),
    						SourceImage: proto.String(sourceImage),
    					},
    					AutoDelete: proto.Bool(true),
    					Boot:       proto.Bool(true),
    					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
    				},
    			},
    			MachineType:    proto.String(machineType),
    			MinCpuPlatform: proto.String("Intel Cascade Lake"),
    			Name:           proto.String(instanceName),
    			NetworkInterfaces: []*computepb.NetworkInterface{
    				{
    					Name: proto.String("global/networks/default"),
    				},
    			},
    			// specifies particular reservation, which should be consumed
    			ReservationAffinity: &computepb.ReservationAffinity{
    				ConsumeReservationType: proto.String("SPECIFIC_RESERVATION"),
    				Key:                    proto.String("compute.googleapis.com/reservation-name"),
    				Values:                 []string{sharedReservation},
    			},
    		},
    	}
    
    	op, err := client.Insert(ctx, req)
    	if err != nil {
    		return fmt.Errorf("unable to create instance: %w", err)
    	}
    
    	if op != nil {
    		if err = op.Wait(ctx); err != nil {
    			return fmt.Errorf("unable to wait for the operation: %w", err)
    		}
    	}
    	fmt.Fprintf(w, "Instance created from shared reservation\n")
    
    	return nil
    }
    

Java

Contoh berikut menunjukkan cara membuat instance N1 dengan empat vCPU, dan Intel Skylake sebagai platform CPU minimum, di zona us-central1-a untuk menggunakan pemesanan tertentu yang cocok:

  • Untuk membuat contoh reservasi sebagai reservasi satu project, dan membuat instance untuk menggunakannya, gunakan contoh kode berikut:

    import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.SPECIFIC_RESERVATION;
    
    import com.google.api.gax.longrunning.OperationFuture;
    import com.google.cloud.compute.v1.AttachedDisk;
    import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
    import com.google.cloud.compute.v1.InsertInstanceRequest;
    import com.google.cloud.compute.v1.Instance;
    import com.google.cloud.compute.v1.InstancesClient;
    import com.google.cloud.compute.v1.NetworkInterface;
    import com.google.cloud.compute.v1.Operation;
    import com.google.cloud.compute.v1.ReservationAffinity;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class ConsumeSingleProjectReservation {
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(developer): Replace these variables before running the sample.
        // Project ID or project number of the Cloud project you want to use.
        String projectId = "YOUR_PROJECT_ID";
        // Name of the zone where the reservation is located.
        String zone = "us-central1-a";
        // Name of the reservation you want to query.
        String reservationName = "YOUR_RESERVATION_NAME";
        // Name of the VM instance you want to query.
        String instanceName = "YOUR_INSTANCE_NAME";
        // machineType: machine type of the VM being created.
        // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
        String machineTypeName = "n1-standard-4";
        // sourceImage: path to the operating system image to mount.
        // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
        String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
        // diskSizeGb: storage size of the boot disk to attach to the instance.
        long diskSizeGb = 10L;
        // networkName: network interface to associate with the instance.
        String networkName = "default";
        // Minimum CPU platform of the instances.
        String minCpuPlatform = "Intel Skylake";
    
        createInstanceAsync(projectId, zone, instanceName, reservationName, machineTypeName,
            sourceImage, diskSizeGb, networkName, minCpuPlatform);
      }
    
      // Create a virtual machine targeted with the reserveAffinity field.
      // Ensure that the VM's properties match the reservation's VM properties.
      public static Instance createInstanceAsync(String projectId, String zone, String instanceName,
          String reservationName, String machineTypeName, String sourceImage, long diskSizeGb,
          String networkName, String minCpuPlatform)
          throws IOException, InterruptedException, ExecutionException, TimeoutException {
        String machineType = String.format("zones/%s/machineTypes/%s", zone, machineTypeName);
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (InstancesClient instancesClient = InstancesClient.create()) {
          AttachedDisk disk =
              AttachedDisk.newBuilder()
                  .setBoot(true)
                  .setAutoDelete(true)
                  .setType(AttachedDisk.Type.PERSISTENT.toString())
                  .setDeviceName("disk-1")
                  .setInitializeParams(
                      AttachedDiskInitializeParams.newBuilder()
                          .setSourceImage(sourceImage)
                          .setDiskSizeGb(diskSizeGb)
                          .build())
                  .build();
    
          NetworkInterface networkInterface = NetworkInterface.newBuilder()
              .setName(networkName)
              .build();
    
          ReservationAffinity reservationAffinity =
              ReservationAffinity.newBuilder()
                  .setConsumeReservationType(SPECIFIC_RESERVATION.toString())
                  .setKey("compute.googleapis.com/reservation-name")
                  // Set specific reservation
                  .addValues(reservationName)
                  .build();
    
          Instance instanceResource =
              Instance.newBuilder()
                  .setName(instanceName)
                  .setMachineType(machineType)
                  .addDisks(disk)
                  .addNetworkInterfaces(networkInterface)
                  .setMinCpuPlatform(minCpuPlatform)
                  .setReservationAffinity(reservationAffinity)
                  .build();
    
          InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
              .setProject(projectId)
              .setZone(zone)
              .setInstanceResource(instanceResource)
              .build();
    
          OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
              insertInstanceRequest);
          Operation response = operation.get(3, TimeUnit.MINUTES);
    
          if (response.hasError()) {
            return null;
          }
          return instancesClient.get(projectId, zone, instanceName);
        }
      }
    }
  • Untuk membuat contoh reservasi sebagai reservasi bersama, dan membuat instance untuk menggunakannya, gunakan contoh kode berikut:

    import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.SPECIFIC_RESERVATION;
    
    import com.google.api.gax.longrunning.OperationFuture;
    import com.google.cloud.compute.v1.AttachedDisk;
    import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
    import com.google.cloud.compute.v1.InsertInstanceRequest;
    import com.google.cloud.compute.v1.Instance;
    import com.google.cloud.compute.v1.InstancesClient;
    import com.google.cloud.compute.v1.NetworkInterface;
    import com.google.cloud.compute.v1.Operation;
    import com.google.cloud.compute.v1.ReservationAffinity;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class ConsumeSpecificSharedReservation {
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(developer): Replace these variables before running the sample.
        // Project ID or project number of the Cloud project you want to use.
        String projectId = "YOUR_PROJECT_ID";
        // Name of the zone the reservation is located.
        String zone = "us-central1-a";
        // Name of the reservation you want to query.
        String reservationName = "YOUR_RESERVATION_NAME";
        // Name of the VM instance you want to query.
        String instanceName = "YOUR_INSTANCE_NAME";
        // machineType: machine type of the VM being created.
        // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
        String machineTypeName = "n1-standard-4";
        // sourceImage: path to the operating system image to mount.
        // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
        String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
        // diskSizeGb: storage size of the boot disk to attach to the instance.
        long diskSizeGb = 10L;
        // networkName: network interface to associate with the instance.
        String networkName = "default";
        // Minimum CPU platform of the instances.
        String minCpuPlatform = "Intel Skylake";
    
        createInstanceAsync(projectId, zone, instanceName, reservationName, machineTypeName,
            sourceImage, diskSizeGb, networkName, minCpuPlatform);
      }
    
      // Create a virtual machine targeted with the reserveAffinity field.
      // Ensure that the VM's properties match the reservation's VM properties.
      public static Instance createInstanceAsync(String projectId, String zone, String instanceName,
          String reservationName, String machineTypeName, String sourceImage, long diskSizeGb,
          String networkName, String minCpuPlatform)
          throws IOException, InterruptedException, ExecutionException, TimeoutException {
        String machineType = String.format("zones/%s/machineTypes/%s", zone, machineTypeName);
        // To consume this reservation from any consumer projects that this reservation is shared with,
        // you must also specify the owner project of the reservation - the path to the reservation.
        String reservationPath =
            String.format("projects/%s/reservations/%s", projectId, reservationName);
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (InstancesClient instancesClient = InstancesClient.create()) {
          AttachedDisk disk =
              AttachedDisk.newBuilder()
                  .setBoot(true)
                  .setAutoDelete(true)
                  .setType(AttachedDisk.Type.PERSISTENT.toString())
                  .setDeviceName("disk-1")
                  .setInitializeParams(
                      AttachedDiskInitializeParams.newBuilder()
                          .setSourceImage(sourceImage)
                          .setDiskSizeGb(diskSizeGb)
                          .build())
                  .build();
    
          NetworkInterface networkInterface = NetworkInterface.newBuilder()
              .setName(networkName)
              .build();
    
          ReservationAffinity reservationAffinity =
              ReservationAffinity.newBuilder()
                  .setConsumeReservationType(SPECIFIC_RESERVATION.toString())
                  .setKey("compute.googleapis.com/reservation-name")
                  // Set specific reservation
                  .addValues(reservationPath)
                  .build();
    
          Instance instanceResource =
              Instance.newBuilder()
                  .setName(instanceName)
                  .setMachineType(machineType)
                  .addDisks(disk)
                  .addNetworkInterfaces(networkInterface)
                  .setMinCpuPlatform(minCpuPlatform)
                  .setReservationAffinity(reservationAffinity)
                  .build();
    
          InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
              .setProject(projectId)
              .setZone(zone)
              .setInstanceResource(instanceResource)
              .build();
    
          OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
              insertInstanceRequest);
          Operation response = operation.get(3, TimeUnit.MINUTES);
    
          if (response.hasError()) {
            return null;
          }
          return instancesClient.get(projectId, zone, instanceName);
        }
      }
    }

Node.js

Contoh berikut menunjukkan cara membuat instance N1 dengan 4 vCPU, dan Intel Skylake sebagai platform CPU minimum, di zona us-central1-a untuk menggunakan pemesanan tertentu yang cocok:

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

// Instantiate a reservationsClient
const instancesClient = new computeLib.InstancesClient();
// Instantiate a zoneOperationsClient
const zoneOperationsClient = new computeLib.ZoneOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The ID of the project where you want to create instance.
const projectId = await instancesClient.getProjectId();
// The zone in which to create instance.
const zone = 'us-central1-a';
// The name of the instance to create.
// const instanceName = 'instance-01';
// The name of the reservation to consume.
// Ensure that the specificReservationRequired field in reservation properties is set to true.
// const reservationName = 'reservation-01';
// Machine type to use for VM.
const machineType = 'n1-standard-4';

// Create instance to consume a specific single-project reservation
async function callCreateInstanceToConsumeSingleProjectReservation() {
  // Describe the size and source image of the boot disk to attach to the instance.
  // Ensure that the VM's properties match the reservation's VM properties,
  // including the zone, machine type (machine family, vCPUs, and memory),
  // minimum CPU platform, GPU amount and type, and local SSD interface and size
  const disk = new compute.Disk({
    boot: true,
    autoDelete: true,
    type: 'PERSISTENT',
    initializeParams: {
      diskSizeGb: '10',
      sourceImage: 'projects/debian-cloud/global/images/family/debian-12',
    },
  });

  //  Define networkInterface
  const networkInterface = new compute.NetworkInterface({
    name: 'global/networks/default',
  });

  // Define reservationAffinity
  const reservationAffinity = new compute.ReservationAffinity({
    consumeReservationType: 'SPECIFIC_RESERVATION',
    key: 'compute.googleapis.com/reservation-name',
    values: [reservationName],
  });

  // Create an instance
  const instance = new compute.Instance({
    name: instanceName,
    machineType: `zones/${zone}/machineTypes/${machineType}`,
    minCpuPlatform: 'Intel Skylake',
    disks: [disk],
    networkInterfaces: [networkInterface],
    reservationAffinity,
  });

  const [response] = await instancesClient.insert({
    project: projectId,
    instanceResource: instance,
    zone,
  });

  let operation = response.latestResponse;

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

  console.log(`Instance ${instanceName} created.`);
}

await callCreateInstanceToConsumeSingleProjectReservation();

Python

Contoh berikut menunjukkan cara membuat instance N2 dengan 32 vCPU, dan Intel Cascade Lake sebagai platform CPU minimum, di zona us-central1-a untuk menggunakan reservasi tertentu yang cocok:

Untuk membuat contoh reservasi khusus dan menggunakannya, lakukan hal berikut:

  • Untuk membuat dan menggunakan contoh reservasi sebagai pemesanan satu project, gunakan contoh kode berikut:

    from __future__ import annotations
    
    import sys
    from typing import Any
    
    from google.api_core.extended_operation import ExtendedOperation
    from google.cloud import compute_v1
    
    
    def wait_for_extended_operation(
        operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
    ) -> Any:
        """
        Waits for the extended (long-running) operation to complete.
    
        If the operation is successful, it will return its result.
        If the operation ends with an error, an exception will be raised.
        If there were any warnings during the execution of the operation
        they will be printed to sys.stderr.
    
        Args:
            operation: a long-running operation you want to wait on.
            verbose_name: (optional) a more verbose name of the operation,
                used only during error and warning reporting.
            timeout: how long (in seconds) to wait for operation to finish.
                If None, wait indefinitely.
    
        Returns:
            Whatever the operation.result() returns.
    
        Raises:
            This method will raise the exception received from `operation.exception()`
            or RuntimeError if there is no exception set, but there is an `error_code`
            set for the `operation`.
    
            In case of an operation taking longer than `timeout` seconds to complete,
            a `concurrent.futures.TimeoutError` will be raised.
        """
        result = operation.result(timeout=timeout)
    
        if operation.error_code:
            print(
                f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
                file=sys.stderr,
                flush=True,
            )
            print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
            raise operation.exception() or RuntimeError(operation.error_message)
    
        if operation.warnings:
            print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
            for warning in operation.warnings:
                print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)
    
        return result
    
    
    def consume_specific_single_project_reservation(
        project_id: str,
        zone: str,
        reservation_name: str,
        instance_name: str,
        machine_type: str = "n1-standard-1",
        min_cpu_platform: str = "Intel Ivy Bridge",
    ) -> compute_v1.Instance:
        """
        Creates a specific reservation in a single project and launches a VM
        that consumes the newly created reservation.
        Args:
            project_id (str): The ID of the Google Cloud project.
            zone (str): The zone to create the reservation.
            reservation_name (str): The name of the reservation to create.
            instance_name (str): The name of the instance to create.
            machine_type (str): The machine type for the instance.
            min_cpu_platform (str): The minimum CPU platform for the instance.
        """
        instance_properties = (
            compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
                machine_type=machine_type,
                min_cpu_platform=min_cpu_platform,
            )
        )
    
        reservation = compute_v1.Reservation(
            name=reservation_name,
            specific_reservation=compute_v1.AllocationSpecificSKUReservation(
                count=3,
                instance_properties=instance_properties,
            ),
            # Only VMs that target the reservation by name can consume from this reservation
            specific_reservation_required=True,
        )
    
        # Create a reservation client
        client = compute_v1.ReservationsClient()
        operation = client.insert(
            project=project_id,
            zone=zone,
            reservation_resource=reservation,
        )
        wait_for_extended_operation(operation, "Reservation creation")
    
        instance = compute_v1.Instance()
        instance.name = instance_name
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
        instance.min_cpu_platform = min_cpu_platform
        instance.zone = zone
    
        # Set the reservation affinity to target the specific reservation
        instance.reservation_affinity = compute_v1.ReservationAffinity(
            consume_reservation_type="SPECIFIC_RESERVATION",  # Type of reservation to consume
            key="compute.googleapis.com/reservation-name",  # Key for the reservation
            values=[reservation_name],  # Reservation name to consume
        )
        # Define the disks for the instance
        instance.disks = [
            compute_v1.AttachedDisk(
                boot=True,  # Indicates that this is a boot disk
                auto_delete=True,  # The disk will be deleted when the instance is deleted
                initialize_params=compute_v1.AttachedDiskInitializeParams(
                    source_image="projects/debian-cloud/global/images/family/debian-11",
                    disk_size_gb=10,
                ),
            )
        ]
        instance.network_interfaces = [
            compute_v1.NetworkInterface(
                network="global/networks/default",  # The network to use
                access_configs=[
                    compute_v1.AccessConfig(
                        name="External NAT",  # Name of the access configuration
                        type="ONE_TO_ONE_NAT",  # Type of access configuration
                    )
                ],
            )
        ]
        # Create a request to insert the instance
        request = compute_v1.InsertInstanceRequest()
        request.zone = zone
        request.project = project_id
        request.instance_resource = instance
    
        vm_client = compute_v1.InstancesClient()
        operation = vm_client.insert(request)
        wait_for_extended_operation(operation, "instance creation")
        print(f"Instance {instance_name} with specific reservation created successfully.")
    
        return vm_client.get(project=project_id, zone=zone, instance=instance_name)
    
    
  • Untuk membuat dan menggunakan contoh reservasi sebagai reservasi bersama, gunakan contoh kode berikut:

    from __future__ import annotations
    
    import sys
    from typing import Any
    
    from google.api_core.extended_operation import ExtendedOperation
    from google.cloud import compute_v1
    
    
    def wait_for_extended_operation(
        operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
    ) -> Any:
        """
        Waits for the extended (long-running) operation to complete.
    
        If the operation is successful, it will return its result.
        If the operation ends with an error, an exception will be raised.
        If there were any warnings during the execution of the operation
        they will be printed to sys.stderr.
    
        Args:
            operation: a long-running operation you want to wait on.
            verbose_name: (optional) a more verbose name of the operation,
                used only during error and warning reporting.
            timeout: how long (in seconds) to wait for operation to finish.
                If None, wait indefinitely.
    
        Returns:
            Whatever the operation.result() returns.
    
        Raises:
            This method will raise the exception received from `operation.exception()`
            or RuntimeError if there is no exception set, but there is an `error_code`
            set for the `operation`.
    
            In case of an operation taking longer than `timeout` seconds to complete,
            a `concurrent.futures.TimeoutError` will be raised.
        """
        result = operation.result(timeout=timeout)
    
        if operation.error_code:
            print(
                f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
                file=sys.stderr,
                flush=True,
            )
            print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
            raise operation.exception() or RuntimeError(operation.error_message)
    
        if operation.warnings:
            print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
            for warning in operation.warnings:
                print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)
    
        return result
    
    
    def consume_specific_shared_project_reservation(
        owner_project_id: str,
        shared_project_id: str,
        zone: str,
        reservation_name: str,
        instance_name: str,
        machine_type: str = "n1-standard-1",
        min_cpu_platform: str = "Intel Ivy Bridge",
    ) -> compute_v1.Instance:
        """
        Creates a specific reservation in a single project and launches a VM
        that consumes the newly created reservation.
        Args:
            owner_project_id (str): The ID of the Google Cloud project.
            shared_project_id: The ID of the owner project of the reservation in the same zone.
            zone (str): The zone to create the reservation.
            reservation_name (str): The name of the reservation to create.
            instance_name (str): The name of the instance to create.
            machine_type (str): The machine type for the instance.
            min_cpu_platform (str): The minimum CPU platform for the instance.
        """
        instance_properties = (
            compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
                machine_type=machine_type,
                min_cpu_platform=min_cpu_platform,
            )
        )
    
        reservation = compute_v1.Reservation(
            name=reservation_name,
            specific_reservation=compute_v1.AllocationSpecificSKUReservation(
                count=3,
                instance_properties=instance_properties,
            ),
            # Only VMs that target the reservation by name can consume from this reservation
            specific_reservation_required=True,
            share_settings=compute_v1.ShareSettings(
                share_type="SPECIFIC_PROJECTS",
                project_map={
                    shared_project_id: compute_v1.ShareSettingsProjectConfig(
                        project_id=shared_project_id
                    )
                },
            ),
        )
    
        # Create a reservation client
        client = compute_v1.ReservationsClient()
        operation = client.insert(
            project=owner_project_id,
            zone=zone,
            reservation_resource=reservation,
        )
        wait_for_extended_operation(operation, "Reservation creation")
    
        instance = compute_v1.Instance()
        instance.name = instance_name
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
        instance.min_cpu_platform = min_cpu_platform
        instance.zone = zone
    
        # Set the reservation affinity to target the specific reservation
        instance.reservation_affinity = compute_v1.ReservationAffinity(
            consume_reservation_type="SPECIFIC_RESERVATION",  # Type of reservation to consume
            key="compute.googleapis.com/reservation-name",
            # To consume this reservation from any consumer projects, specify the owner project of the reservation
            values=[f"projects/{owner_project_id}/reservations/{reservation_name}"],
        )
        # Define the disks for the instance
        instance.disks = [
            compute_v1.AttachedDisk(
                boot=True,  # Indicates that this is a boot disk
                auto_delete=True,  # The disk will be deleted when the instance is deleted
                initialize_params=compute_v1.AttachedDiskInitializeParams(
                    source_image="projects/debian-cloud/global/images/family/debian-11",
                    disk_size_gb=10,
                ),
            )
        ]
        instance.network_interfaces = [
            compute_v1.NetworkInterface(
                network="global/networks/default",  # The network to use
                access_configs=[
                    compute_v1.AccessConfig(
                        name="External NAT",  # Name of the access configuration
                        type="ONE_TO_ONE_NAT",  # Type of access configuration
                    )
                ],
            )
        ]
        # Create a request to insert the instance
        request = compute_v1.InsertInstanceRequest()
        request.zone = zone
        # The instance will be created in the shared project
        request.project = shared_project_id
        request.instance_resource = instance
    
        vm_client = compute_v1.InstancesClient()
        operation = vm_client.insert(request)
        wait_for_extended_operation(operation, "instance creation")
        print(f"Instance {instance_name} from project {owner_project_id} created.")
        # The instance is created in the shared project, so we return it from there.
        return vm_client.get(project=shared_project_id, zone=zone, instance=instance_name)
    
    

REST

Contoh berikut menunjukkan cara membuat reservasi tertentu di zona us-central1-a untuk tiga instance N2 dengan 32 vCPU, dan Intel Cascade Lake sebagai platform CPU minimum. Contoh ini juga menunjukkan cara membuat satu instance untuk menggunakan reservasi.

Untuk membuat contoh reservasi khusus dan menggunakannya, lakukan hal berikut:

  1. Untuk membuat contoh pemesanan, buat permintaan POST ke metode instances.insert. Dalam isi permintaan, sertakan kolom specificReservationRequired yang ditetapkan ke true:

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations
    
    {
      "name": "reservation-02",
      "specificReservation": {
        "count": "3",
        "instanceProperties": {
          "machineType": "n2-standard-32",
          "minCpuPlatform": "Intel Cascade Lake",
        }
      },
      "specificReservationRequired": true
    }
    
  2. Untuk membuat instance yang menggunakan contoh pemesanan, buat permintaan POST ke metode instances.insert. Dalam isi permintaan, di kolom reservationAffinity, sertakan hal berikut:

    • Kolom consumeReservationType ditetapkan ke SPECIFIC_RESERVATION.

    • Kolom key ditetapkan ke compute.googleapis.com/reservation-name.

    • Kolom values ditetapkan ke URL reservasi.

    Permintaannya mirip dengan berikut ini:

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/instances
    
    {
      "name": "instance-02",
      "machineType": "zones/us-central1-a/machineTypes/n2-standard-32",
      "minCpuPlatform": "Intel Cascade Lake",
      "disks": [
        {
          "boot": true,
          "initializeParams": {
            "sourceImage": "projects/debian-cloud/global/images/family/debian-12"
          }
        }
      ],
      "networkInterfaces": [
        {
          "network": "global/networks/default"
        }
      ],
      "reservationAffinity": {
        "consumeReservationType": "SPECIFIC_RESERVATION",
        "key": "compute.googleapis.com/reservation-name",
        "values": [
          "RESERVATION_URL"
        ]
      }
    }
    

    Ganti RESERVATION_URL dengan URL reservasi. Tentukan salah satu nilai berikut:

    • Jika Anda membuat reservasi di project yang sama: reservation-02

    • Jika reservasi berada di project lain: projects/PROJECT_ID/reservations/reservation-02

Menguji apakah properti instance cocok dengan reservasi yang digunakan secara otomatis

Untuk menguji apakah properti instance komputasi cocok dengan pemesanan yang digunakan secara otomatis, lakukan hal berikut:

  1. Buat salinan reservasi sebagai reservasi yang ditargetkan secara khusus untuk satu instance.

  2. Buat instance pengujian untuk menggunakan reservasi.

Jika Anda dapat membuat instance pengujian, propertinya akan cocok dengan properti reservasi pengujian. Jika tidak, pembuatan instance akan gagal.

Setelah Anda mengonfirmasi bahwa properti instance pengujian dan reservasi pengujian cocok, hapus reservasi dan instance pengujian.

Memverifikasi pemakaian reservasi

Untuk memverifikasi pemakaian reservasi, Anda dapat melakukan satu atau beberapa hal berikut:

  • Untuk melihat jumlah instance komputasi saat ini yang menggunakan reservasi Anda, dan jumlah instance lainnya yang dapat menggunakannya, lihat reservasi.

  • Untuk memantau data pemakaian reservasi yang diperbarui setiap 30 menit, dan menerima pemberitahuan saat reservasi digunakan atau tidak digunakan, pantau pemakaian reservasi.

  • Untuk melihat data penggunaan reservasi yang diperbarui setiap 24 jam, lakukan salah satu hal berikut:

    • Untuk menerima laporan penggunaan di bucket Cloud Storage guna menganalisis tren penggunaan dan mengidentifikasi reservasi yang tidak digunakan, lihat laporan penggunaan reservasi.
    • Untuk melihat konsumsi pemesanan sebelumnya dan yang diprediksi untuk menganalisis tren konsumsi dan merencanakan kebutuhan kapasitas di masa mendatang, gunakan Capacity Planner.

Langkah berikutnya