Consuma le prenotazioni

Questo documento spiega come consumare le prenotazioni in Compute Engine. Per scoprire come consumare le prenotazioni in altri prodotti Google Cloud , consulta la seguente documentazione:

Dopo che hai creato una prenotazione o che Compute Engine ne crea una automaticamente per permetterti di soddisfare una prenotazione futura, Compute Engine trattiene le risorse prenotate per te. Quindi, puoi utilizzare le risorse prenotate per creare istanze Compute Engine corrispondenti alle proprietà della prenotazione. Questa azione è nota come consumo di una prenotazione. Puoi utilizzare la capacità prenotata per creare istanze finché la prenotazione non verrà consumata completamente.

Limitazioni

Non è possibile consumare una prenotazione per creare le seguenti risorse di Compute Engine:

  • VM spot o istanze preemptible

  • Nodi single-tenant

Prima di iniziare

  • Se non l'hai ancora fatto, configura l'autenticazione. L'autenticazione verifica la tua identità per l'accesso a Google Cloud servizi e API. Per eseguire codice o esempi da un ambiente di sviluppo locale, puoi autenticarti su Compute Engine selezionando una delle seguenti opzioni:

    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. Installa Google Cloud CLI. Dopo l'installazione, inizializza Google Cloud CLI eseguendo il seguente comando:

      gcloud init

      Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

    2. Set a default region and zone.

    Vai

    Per utilizzare gli esempi di Go questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.

      Installa Google Cloud CLI.

      Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

      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.

    Per ulteriori informazioni, vedi Set up authentication for a local development environment.

    Java

    Per utilizzare gli esempi di Java questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.

      Installa Google Cloud CLI.

      Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

      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.

    Per ulteriori informazioni, vedi Set up authentication for a local development environment.

    Node.js

    Per utilizzare gli esempi di Node.js questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.

      Installa Google Cloud CLI.

      Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

      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.

    Per ulteriori informazioni, vedi Set up authentication for a local development environment.

    Python

    Per utilizzare gli esempi di Python questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.

      Installa Google Cloud CLI.

      Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

      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.

    Per ulteriori informazioni, vedi Set up authentication for a local development environment.

    REST

    Per utilizzare gli esempi di API REST in questa pagina in un ambiente di sviluppo locale, utilizza le credenziali che fornisci a gcloud CLI.

      Installa Google Cloud CLI.

      Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

    Per saperne di più, consulta Autenticarsi per l'utilizzo di REST nella documentazione sull'autenticazione di Google Cloud .

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per utilizzare le prenotazioni, chiedi all'amministratore di concederti il ruolo IAM Compute Instance Admin (v1) (roles/compute.instanceAdmin.v1) nel progetto. Per saperne di più sulla concessione dei ruoli, consulta Gestisci l'accesso a progetti, cartelle e organizzazioni.

Questo ruolo predefinito include le autorizzazioni necessarie per consumare le prenotazioni. Per vedere quali sono esattamente le autorizzazioni richieste, espandi la sezione Autorizzazioni obbligatorie:

Autorizzazioni obbligatorie

Per consumare le prenotazioni sono necessarie le seguenti autorizzazioni:

  • Per creare prenotazioni: compute.reservations.create sul progetto
  • Per creare istanze:
    • compute.instances.create sul progetto
    • Per utilizzare un'immagine personalizzata per creare la VM: compute.images.useReadOnly sull'immagine
    • Per utilizzare uno snapshot per creare la VM: compute.snapshots.useReadOnly sullo snapshot
    • Per utilizzare un template di istanza per creare la VM: compute.instanceTemplates.useReadOnly sul template di istanza
    • Per assegnare una rete legacy alla VM: compute.networks.use sul progetto
    • Per specificare un indirizzo IP statico per la VM: compute.addresses.use sul progetto
    • Per assegnare un indirizzo IP esterno alla VM quando viene utilizzata una rete legacy: compute.networks.useExternalIp sul progetto
    • Per specificare una subnet per la VM: compute.subnetworks.use sul progetto o sulla subnet scelta
    • Per assegnare un indirizzo IP esterno alla VM quando viene utilizzata una rete VPC: compute.subnetworks.useExternalIp sul progetto o sulla subnet scelta
    • Per impostare i metadati dell'istanza VM per la VM: compute.instances.setMetadata sul progetto
    • Per impostare i tag per la VM: compute.instances.setTags sulla VM
    • Per impostare le etichette per la VM: compute.instances.setLabels sulla VM
    • Per impostare un service account da utilizzare per la VM: compute.instances.setServiceAccount sulla VM
    • Per creare un nuovo disco per la VM: compute.disks.create sul progetto
    • Per collegare un disco esistente in modalità di sola lettura o lettura/scrittura: compute.disks.use sul disco
    • Per collegare un disco esistente in modalità di sola lettura: compute.disks.useReadOnly sul disco
  • Per creare template di istanze: compute.instanceTemplates.create sul progetto

Potresti anche ottenere queste autorizzazioni con ruoli personalizzati o altri ruoli predefiniti.

Consuma una prenotazione

Gli esempi nelle sezioni seguenti mostrano come consumare una prenotazione creando una singola istanza di computing. Puoi anche consumare le prenotazioni creando istanze corrispondenti alle proprietà delle prenotazioni mediante un'altra opzione di implementazione oppure aggiornando le proprietà delle istanze esistenti in modo che corrispondano alle prenotazioni consumate automaticamente.

Per consumare una prenotazione, applica uno dei seguenti metodi:

Consuma una prenotazione consumata automaticamente

Le prenotazioni consumate automaticamente consentono a qualsiasi istanza di calcolo che corrisponde alle proprietà della prenotazione di utilizzarla automaticamente. Questo comportamento di consumo si applica sia alle istanze nuove sia a quelle esistenti e in esecuzione. Questo tipo di prenotazione viene applicato per impostazione predefinita quando crei prenotazioni o quando Compute Engine ne crea una automaticamente per soddisfare una prenotazione futura.

In caso di corrispondenza tra le proprietà di una prenotazione automatica per un singolo progetto e quelle di una prenotazione automatica condivisa, le istanze del progetto consumano prima la prenotazione per un singolo progetto e poi la prenotazione condivisa. Per ulteriori informazioni, consulta l'ordine di consumo per le prenotazioni.

Per creare e consumare una prenotazione automatica di esempio, seleziona una delle seguenti opzioni:

Console

L'esempio seguente mostra come creare una prenotazione automatica nella zona us-central1-a per tre istanze N2 con 32 vCPU e Intel Cascade Lake come piattaforma CPU minima. L'esempio mostra anche come creare una singola istanza per consumare la prenotazione.

Per creare la prenotazione automatica di esempio e consumarla, segui questi passaggi:

  1. Per creare una prenotazione di esempio, completa i seguenti passaggi:

    1. Nella console Google Cloud , vai alla pagina Prenotazioni.

      Vai a Prenotazioni

      I passaggi rimanenti vengono visualizzati automaticamente nella console Google Cloud .

    2. Nella scheda Prenotazioni on demand (predefinita), fai clic su Crea prenotazione. Viene visualizzata la pagina Crea una prenotazione.

    3. Nel campo Nome, inserisci un nome per la prenotazione. Ad esempio, inserisci reservation-01.

    4. Seleziona la Regione e la Zona in cui prenotare le risorse. Ad esempio, seleziona rispettivamente us-central1 e us-central1-a.

    5. Nella sezione Tipo di condivisione, esegui una delle seguenti operazioni:

      • Per creare una prenotazione per un singolo progetto, seleziona Locali.

      • Per creare una prenotazione condivisa, seleziona Condivisa e specifica i progetti con cui vuoi condividerla.

    6. Nella sezione Utilizza con un'istanza VM, seleziona l'opzione Usa automaticamente la prenotazione, se non è già selezionata.

    7. Nel campo Numero di istanze VM, inserisci 3.

    8. Nella scheda Uso generico, seleziona N2.

    9. Nella sezione Tipo di macchina, sulla scheda Predefinito (predefinita), seleziona n2-standard-32.

    10. Espandi Piattaforma CPU e GPU e, nel campo Piattaforma CPU, seleziona Intel Cascade Lake o versioni successive.

    11. Fai clic su Crea.

  2. Per creare un'istanza che consuma la prenotazione di esempio, completa i seguenti passaggi:

    1. Nella console Google Cloud , vai alla pagina Crea un'istanza.

      Vai a Crea un'istanza

      Viene visualizzata la pagina Crea un'istanza, che contiene il riquadro Configurazione macchina.

    2. Nel riquadro Configurazione macchina, segui questi passaggi:

      1. Nel campo Nome, inserisci un nome per l'istanza. Per questo esempio, inserisci instance-01.

      2. Specifica la Regione e la Zona in cui prenotare le risorse. Per questo esempio, seleziona rispettivamente us-central1 e us-central1-a.

      3. Nella scheda Uso generico, seleziona N2.

      4. Nella sezione Tipo di macchina, sulla scheda Predefinito (predefinita), seleziona n2-standard-32.

      5. Espandi la sezione Opzioni avanzate e poi, nel campo Piattaforma CPU, seleziona Intel Cascade Lake o versioni successive.

    3. (Facoltativo) L'utilizzo automatico di una prenotazione corrispondente è l'impostazione predefinita. Tuttavia, se vuoi specificare questa impostazione, procedi nel seguente modo:

      1. Nel menu di navigazione, fai clic su Avanzate. Viene visualizzato il riquadro Avanzate.

      2. Nella sezione Prenotazioni, seleziona Utilizza la selezione automatica.

    4. Fai clic su Crea.

gcloud

L'esempio seguente mostra come creare una prenotazione automatica nella zona us-central1-a per tre istanze N2 con 32 vCPU e Intel Cascade Lake come piattaforma CPU minima. L'esempio mostra anche come creare una singola istanza per consumare la prenotazione.

Per creare la prenotazione automatica di esempio e consumarla, segui questi passaggi:

  1. Per creare la prenotazione di esempio, utilizza il comando 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. Per creare un'istanza che consumi la prenotazione di esempio, utilizza il comando gcloud compute instances create con il flag --reservation-affinity impostato su any. Poiché any è la configurazione predefinita, puoi anche omettere questo flag.

    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

Per creare la prenotazione automatica di esempio usando un template di istanza e creare poi un'istanza per consumare la prenotazione con lo stesso template, utilizza il seguente esempio di codice:

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

L'esempio seguente mostra come creare un'istanza N1 con quattro vCPU e Intel Skylake come piattaforma CPU minima nella zona us-central1-a. L'istanza consuma automaticamente una prenotazione corrispondente.

Per creare l'istanza di esempio, utilizza il seguente esempio di codice:

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

L'esempio seguente mostra come creare un'istanza N1 con quattro vCPU e Intel Skylake come piattaforma CPU minima nella zona us-central1-a. L'istanza consuma automaticamente una prenotazione corrispondente.

Per creare l'istanza di esempio, utilizza il seguente esempio di codice:

// 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

L'esempio seguente mostra come creare una prenotazione automatica nella zona us-central1-a per tre istanze N1 con una vCPU e Intel Ivy come piattaforma CPU minima. L'esempio mostra anche come creare una singola istanza per consumare la prenotazione.

Per creare la prenotazione automatica di esempio e consumarla, segui questi passaggi:

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

L'esempio seguente mostra come creare una prenotazione automatica nella zona us-central1-a per tre istanze N2 con 32 vCPU e Intel Cascade Lake come piattaforma CPU minima. L'esempio mostra anche come creare una singola istanza per consumare la prenotazione.

Per creare la prenotazione automatica di esempio e consumarla, segui questi passaggi:

  1. Per creare la prenotazione di esempio, invia una richiesta POST al metodo 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. Per creare un'istanza che consumi la prenotazione di esempio, invia una richiesta POST al metodo instances.insert. Nel corpo della richiesta, includi il campo consumeReservationType impostato su ANY_RESERVATION. Tuttavia, poiché ANY_RESERVATION è la configurazione predefinita, puoi anche omettere questo campo.

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

Consuma una prenotazione con target specifico

Le prenotazioni con target specifico consentono alle nuove istanze di computing che corrispondono alle proprietà della prenotazione e hanno come target la prenotazione di consumarla. La creazione delle istanze ha esito positivo solo se le loro proprietà corrispondono a quelle della prenotazione. In caso contrario, si verificano degli errori.

A seconda del metodo di creazione che vuoi utilizzare, crea prenotazioni specifiche e istanze che le assumono come target nel modo seguente:

Metodo di creazione Quando crei una prenotazione Quando crei istanze per consumare la prenotazione
ConsoleGoogle Cloud Nella sezione Utilizza con un'istanza VM, seleziona Seleziona una prenotazione specifica. Nel riquadro Avanzato, nella sezione Prenotazioni, seleziona Scegli una prenotazione. Poi, segui le istruzioni per selezionare una prenotazione.
Google Cloud CLI Includi il flag --require-specific-reservation. Includi i seguenti flag:
  • Il flag --reservation-affinity impostato su specific.
  • Il flag --reservation impostato sul percorso della risorsa alla prenotazione, formattato come projects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
Vai Includi il campo SpecificReservationRequired impostato su true. Nel campo ReservationAffinity, includi i seguenti campi:
  • Il campo ConsumeReservationType impostato su SPECIFIC_RESERVATION.
  • Il campo Key impostato su compute.googleapis.com/reservation-name.
  • Il campo Values impostato sul percorso della risorsa alla prenotazione, formattato come projects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
Java Includi il campo setSpecificReservationRequired impostato su true. Nel campo ReservationAffinity, includi i seguenti campi:
  • Il campo setConsumeReservationType impostato su SPECIFIC_RESERVATION.
  • Il campo setKey impostato su compute.googleapis.com/reservation-name.
  • Il campo addValues impostato sul percorso della risorsa alla prenotazione, formattato come projects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
Node.js e API REST Includi il campo specificReservationRequired impostato su true. Nel campo reservationAffinity, includi i seguenti campi:
  • Il campo consumeReservationType impostato su SPECIFIC_RESERVATION.
  • Il campo key impostato su compute.googleapis.com/reservation-name.
  • Il campo values impostato su un elenco contenente un singolo elemento con il percorso della risorsa alla prenotazione, formattato come projects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
Python Includi il campo specific_reservation_required impostato su true. Nel campo reservation_affinity, includi i seguenti campi:
  • Il campo consume_reservation_type impostato su SPECIFIC_RESERVATION.
  • Il campo key impostato su compute.googleapis.com/reservation-name.
  • Il campo values impostato sul percorso della risorsa alla prenotazione, formattato come projects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
Terraform Includi il campo specific_reservation_required impostato su true. Nel campo reservation_affinity, includi i seguenti campi:
  • Il campo type impostato su SPECIFIC_RESERVATION.
  • Il campo specific_reservation, che include i seguenti campi:
    • Il campo key impostato su compute.googleapis.com/reservation-name.
    • Il campo values impostato su un elenco contenente un singolo elemento con il percorso della risorsa alla prenotazione, formattato come projects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.

Per creare una specifica prenotazione di esempio e un'istanza per consumarla, seleziona una delle seguenti opzioni:

Console

L'esempio seguente mostra come creare una prenotazione specifica nella zona us-central1-a per tre istanze N2 con 32 vCPU e Intel Cascade Lake come piattaforma CPU minima. L'esempio mostra anche come creare una singola istanza per consumare la prenotazione.

Per creare la prenotazione specifica di esempio e consumarla, segui questi passaggi:

  1. Per creare una prenotazione di esempio, completa i seguenti passaggi:

    1. Nella console Google Cloud , vai alla pagina Prenotazioni.

      Vai a Prenotazioni

      I passaggi rimanenti vengono visualizzati automaticamente nella console Google Cloud .

    2. Nella scheda Prenotazioni on demand (predefinita), fai clic su Crea prenotazione. Viene visualizzata la pagina Crea una prenotazione.

    3. Nel campo Nome, inserisci un nome per la prenotazione. Ad esempio, inserisci reservation-02.

    4. Specifica la Regione e la Zona in cui prenotare le risorse. Per questo esempio, seleziona rispettivamente us-central1 e us-central1-a.

    5. Nella sezione Tipo di condivisione, esegui una delle seguenti operazioni:

      • Per creare una prenotazione per un singolo progetto, seleziona Locali.

      • Per creare una prenotazione condivisa, seleziona Condivisa e specifica i progetti con cui vuoi condividerla.

    6. Nella sezione Utilizza con un'istanza VM, scegli Seleziona una prenotazione specifica.

    7. Nel campo Numero di istanze VM, inserisci 3.

    8. Nella scheda Uso generico, seleziona N2.

    9. Nella sezione Tipo di macchina, sulla scheda Predefinito (predefinita), seleziona n2-standard-32.

    10. Espandi Piattaforma CPU e GPU e, nel campo Piattaforma CPU, seleziona Intel Cascade Lake o versioni successive.

    11. Fai clic su Crea.

  2. Per creare un'istanza che consuma la prenotazione di esempio, completa i seguenti passaggi:

    1. Nella console Google Cloud , vai alla pagina Crea un'istanza.

      Vai a Crea un'istanza

      Viene visualizzata la pagina Crea un'istanza, che contiene il riquadro Configurazione macchina.

    2. Nel riquadro Configurazione macchina, segui questi passaggi:

      1. Nel campo Nome, inserisci un nome per l'istanza. Per questo esempio, inserisci instance-02.

      2. Specifica la Regione e la Zona in cui prenotare le risorse. Per questo esempio, seleziona rispettivamente us-central1 e us-central1-a.

      3. Nella scheda Uso generico, seleziona N2.

      4. Nella sezione Tipo di macchina, sulla scheda Predefinito (predefinita), seleziona n2-standard-32.

      5. Espandi la sezione Opzioni avanzate e poi, nel campo Piattaforma CPU, seleziona Intel Cascade Lake o versioni successive.

    3. Nel menu di navigazione, fai clic su Avanzate. Viene visualizzato il riquadro Avanzate.

    4. Nella sezione Prenotazioni, seleziona Scegli una prenotazione, quindi fai clic su Scegli prenotazione.

    5. Nel riquadro Scegli una prenotazione visualizzato, segui questi passaggi:

      1. Seleziona la prenotazione specifica che hai creato nei passaggi precedenti. Se vuoi consumare una prenotazione condivisa già esistente in un altro progetto, seleziona il progetto che include la prenotazione nell'elenco Progetto.

      2. Fai clic su Scegli.

    6. Fai clic su Crea.

gcloud

L'esempio seguente mostra come creare una prenotazione specifica nella zona us-central1-a per tre istanze N2 con 32 vCPU e Intel Cascade Lake come piattaforma CPU minima. L'esempio mostra anche come creare una singola istanza per consumare la prenotazione.

Per creare la prenotazione specifica di esempio e consumarla, segui questi passaggi:

  1. Per creare la prenotazione di esempio, utilizza il comando gcloud compute reservations create con il 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. Per creare un'istanza che consumi la prenotazione di esempio, utilizza il comando gcloud compute instances create con i flag --reservation e --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
    

    Sostituisci RESERVATION_URL con l'URL della prenotazione. Specifica uno dei seguenti valori:

    • Se hai creato la prenotazione nello stesso progetto: reservation-02

    • Se la prenotazione si trova in un progetto diverso: projects/PROJECT_ID/reservations/reservation-02

Go

Gli esempi seguenti mostrano come creare un'istanza N2 con 32 vCPU e Intel Cascade Lake come piattaforma CPU minima nella zona us-central1-a per consumare una prenotazione specifica corrispondente:

  • Per creare l'istanza di esempio che consuma una prenotazione specifica per un singolo progetto, usa il seguente esempio di codice:

    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
    }
    
  • Per creare l'istanza di esempio allo scopo di consumare una prenotazione specifica condivisa, utilizza il seguente esempio di codice:

    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

Gli esempi seguenti mostrano come creare un'istanza N1 con quattro vCPU e Intel Skylake come piattaforma CPU minima nella zona us-central1-a per consumare una prenotazione specifica corrispondente:

  • Per creare una prenotazione di esempio come prenotazione per un singolo progetto e un'istanza per consumarla, usa il seguente esempio di codice:

    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);
        }
      }
    }
  • Per creare una prenotazione di esempio come prenotazione condivisa e un'istanza per consumarla, utilizza il seguente esempio di codice:

    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

Gli esempi seguenti mostrano come creare un'istanza N1 con 4 vCPU e Intel Skylake come piattaforma CPU minima nella zona us-central1-a per consumare una prenotazione specifica corrispondente:

// 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

Gli esempi seguenti mostrano come creare un'istanza N2 con 32 vCPU e Intel Cascade Lake come piattaforma CPU minima nella zona us-central1-a per consumare una prenotazione specifica corrispondente:

Per creare la prenotazione specifica di esempio e consumarla, segui questi passaggi:

  • Per creare e consumare la prenotazione di esempio come prenotazione per un singolo progetto, utilizza il seguente esempio di codice:

    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)
    
    
  • Per creare e consumare la prenotazione di esempio come prenotazione condivisa, utilizza il seguente esempio di codice:

    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

L'esempio seguente mostra come creare una prenotazione specifica nella zona us-central1-a per tre istanze N2 con 32 vCPU e Intel Cascade Lake come piattaforma CPU minima. L'esempio mostra anche come creare una singola istanza per consumare la prenotazione.

Per creare la prenotazione specifica di esempio e consumarla, segui questi passaggi:

  1. Per creare la prenotazione di esempio, invia una richiesta POST al metodo instances.insert. Nel corpo della richiesta, includi il campo specificReservationRequired impostato su 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. Per creare un'istanza che consumi la prenotazione di esempio, invia una richiesta POST al metodo instances.insert. Includi quanto segue nel campo reservationAffinity del corpo della richiesta:

    • Il campo consumeReservationType impostato su SPECIFIC_RESERVATION.

    • Il campo key impostato su compute.googleapis.com/reservation-name.

    • Il campo values impostato sull'URL della prenotazione.

    La richiesta è simile alla seguente:

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

    Sostituisci RESERVATION_URL con l'URL della prenotazione. Specifica uno dei seguenti valori:

    • Se hai creato la prenotazione nello stesso progetto: reservation-02

    • Se la prenotazione si trova in un progetto diverso: projects/PROJECT_ID/reservations/reservation-02

Consumare una prenotazione creata automaticamente per una richiesta in modalità calendario

Questo tipo di prenotazione consente alle nuove istanze di computing di utilizzare una prenotazione che Compute Engine crea automaticamente per soddisfare una prenotazione futura in modalità calendario.

Per utilizzare questo tipo di prenotazione, devi creare un'istanza nel seguente modo:

L'esempio seguente crea una richiesta di prenotazione futura in modalità calendario per le istanze A3 Ultra. L'esempio mostra anche i campi da specificare quando crei un'istanza A3 Ultra autonoma per utilizzare la prenotazione creata automaticamente per la richiesta.

Per utilizzare la prenotazione di esempio creata automaticamente, seleziona una delle seguenti opzioni:

Console

  1. Crea una richiesta di esempio per cinque istanze A3 Ultra e inviala per la revisione:

    1. Nella console Google Cloud , vai alla pagina Prenotazioni.

      Vai a Prenotazioni

    2. Fai clic sulla scheda Prenotazioni future.

    3. Fai clic su Crea prenotazione futura. Viene visualizzata la pagina Crea una prenotazione futura.

    4. Nella sezione Configurazione hardware, seleziona Specifica il tipo di macchina, quindi specifica un'istanza A3 Ultra.

    5. Nella sezione Metodo di ottenimento, completa i seguenti passaggi:

      1. Seleziona Cerca la capacità per un massimo di 90 giorni.

      2. Negli elenchi Regione e Zona, specifica la regione e la zona in cui prenotare le risorse. Per questo esempio, seleziona rispettivamente us-central1 e us-central1-a.

      3. Nel campo Capacità totale necessaria, inserisci 5.

      4. Nella sezione Periodo di prenotazione, specifica il periodo di prenotazione.

    6. Specifica i campi rimanenti e fai clic su Invia.

  2. All'ora di inizio della richiesta, per creare un'istanza A3 Ultra che utilizzi la prenotazione creata automaticamente di esempio, procedi nel seguente modo:

    1. Nella console Google Cloud , vai alla pagina Crea un'istanza.

      Vai a Crea un'istanza

    2. Nel campo Nome, inserisci un nome per l'istanza. Per questo esempio, inserisci example-instance.

    3. Specifica la Regione e la Zona in cui vuoi prenotare le risorse. Per questo esempio, seleziona rispettivamente us-central1 e us-central1-a.

    4. Fai clic sulla scheda GPU, quindi seleziona NVIDIA H200 141 GB nell'elenco Tipo di GPU. Questa azione specifica un'istanza A3 Ultra e imposta il modello di provisioning su Con prenotazione.

    5. Nel menu di navigazione, fai clic su Avanzate.

    6. Nella sezione Prenotazioni, seleziona Scegli una prenotazione, quindi fai clic su Scegli una prenotazione.

    7. Nel riquadro Scegli una prenotazione:

      1. Seleziona una prenotazione specifica. Se vuoi utilizzare una prenotazione condivisa esistente in un altro progetto, seleziona il progetto che include la prenotazione nell'elenco Progetto.

      2. Fai clic su Scegli.

    8. Nella sezione Modello di provisioning, espandi la sezione Impostazioni avanzate del modello di provisioning delle VM.

    9. Nell'elenco Alla terminazione della VM, seleziona Arresta (valore predefinito) o Elimina.

    10. Fai clic su Crea.

gcloud

  1. Per creare una richiesta di esempio per cinque VM A3 Ultra e inviarla per la revisione, utilizza il comando gcloud beta compute future-reservations create:

    gcloud beta compute future-reservations create example-fr \
        --auto-delete-auto-created-reservations \
        --deployment-type=DENSE \
        --planning-status=SUBMITTED \
        --require-specific-reservation \
        --reservation-mode=CALENDAR \
        --reservation-name=example-reservation \
        --share-type=local \
        --start-time=2025-10-05T00:00:00Z \
        --end-time=2025-10-19T00:00:00Z \
        --machine-type=a3-ultragpu-8g \
        --total-count=5 \
        --zone=us-central1-a
    

    Supponiamo che Google Cloud approvi la richiesta e Compute Engine crei automaticamente una prenotazione vuota. All'ora di inizio della richiesta, il 5 ottobre 2025, Compute Engine aumenta il numero di VM con GPU prenotate nella prenotazione. Puoi quindi utilizzare la prenotazione.

  2. All'ora di inizio della richiesta, per creare un'istanza A3 Ultra che consumi la prenotazione automatica di esempio, utilizza il comando gcloud compute instances create con i seguenti flag:

    • Il flag --instance-termination-action.

    • Il flag --provisioning-model impostato su RESERVATION_BOUND.

    • Il flag --reservation.

    • Il flag --reservation-affinity impostato su specific.

    Il comando è simile al seguente. Per i requisiti completi per creare un'istanza A3 Ultra, consulta Crea un'istanza A3 Ultra o A4.

    gcloud compute instance create example-instance  \
        --machine-type=a3-ultragpu-8g \
        --instance-termination-action=TERMINATION_ACTION \
        --provisioning-model=RESERVATION_BOUND \
        --reservation-affinity=specific \
        --reservation=RESERVATION_URL \
        --zone=us-central1-a \
        ...
    

    Il comando include i seguenti valori:

    • TERMINATION_ACTION: indica se Compute Engine arresta (STOP) o elimina (DELETE) la VM al termine del periodo di prenotazione.

    • RESERVATION_URL: l'URL della prenotazione, che è formattato nel seguente modo:

      • Se la prenotazione creata automaticamente esiste nel tuo progetto: example-reservation.

      • Se la prenotazione creata automaticamente esiste in un progetto diverso: projects/PROJECT_ID/reservations/example-reservation.

REST

  1. Per creare una richiesta di esempio per cinque istanze A3 Ultra e inviarla per la revisione, invia una richiesta POST al metodo futureReservations.insert beta:

    POST https://compute.googleapis.com/compute/beta/projects/example-project/zones/us-central1-a/futureReservations
    
    {
      "name": "example-request-calendar-mode",
      "autoDeleteAutoCreatedReservations": true,
      "deploymentType": "DENSE",
      "planningStatus": "SUBMITTED",
      "reservationMode": "CALENDAR",
      "reservationName": "example-reservation",
      "shareSettings": {
        "shareType": "LOCAL"
      },
      "specificReservationRequired": true,
      "specificSkuProperties": {
        "machineType": "a3-ultragpu-8g",
        "totalCount": 5
      },
      "timeWindow": {
        "startTime": "2025-10-05T00:00:00Z",
        "endTime": "2025-10-19T00:00:00Z"
      }
    }
    

    Supponiamo che Google Cloud approvi la richiesta e Compute Engine crei automaticamente una prenotazione vuota. All'ora di inizio della richiesta, il 5 ottobre 2025, Compute Engine aumenta il numero di VM con GPU prenotate nella prenotazione. Puoi quindi utilizzare la prenotazione.

  2. All'ora di inizio della richiesta, per creare un'istanza A3 Ultra che utilizzi la prenotazione di esempio creata automaticamente, invia una richiesta POST al metodo instances.insert. Nel corpo della richiesta, includi i seguenti campi:

    • Il campo reservationAffinity.consumeReservationType impostato su SPECIFIC_RESERVATION.

    • Il campo reservationAffinity.key impostato su compute.googleapis.com/reservation-name.

    • Il campo reservationAffinity.values impostato sull'URL della prenotazione.

    • Il campo scheduling.instanceTerminationAction.

    • Il campo scheduling.provisioningModel impostato su RESERVATION_BOUND.

    La richiesta è simile alla seguente. Per i requisiti completi per creare un'istanza A3 Ultra, consulta Crea un'istanza A3 Ultra o A4.

    POST https://compute.googleapis.com/compute/beta/projects/example-project/zones/us-central1-a/
    
    {
      {
        "machineType": "projects/example-project/zones/us-central1-a/machineTypes/a3-ultragpu-8g",
        "name": "example-instance",
        "reservationAffinity": {
          "consumeReservationType": "SPECIFIC_RESERVATION",
          "key": "compute.googleapis.com/reservation-name",
          "values":[
            "RESERVATION_URL"
          ],
        },
        "scheduling": {
          "instanceTerminationAction": "TERMINATION_ACTION",
          "provisioningModel": "RESERVATION_BOUND"
        },
        ...
      }
    }
    

    Il corpo della richiesta include i seguenti valori:

    • RESERVATION_URL: l'URL della prenotazione, che è formattato nel seguente modo:

      • Se la prenotazione creata automaticamente esiste nel tuo progetto: example-reservation.

      • Se la prenotazione creata automaticamente esiste in un progetto diverso: projects/PROJECT_ID/reservations/example-reservation.

    • TERMINATION_ACTION: indica se Compute Engine arresta (STOP) o elimina (DELETE) la VM al termine del periodo di prenotazione.

Verifica che le proprietà dell'istanza corrispondano a una prenotazione consumata automaticamente

Per verificare se le proprietà di un'istanza di calcolo corrispondono a una prenotazione consumata automaticamente, segui questi passaggi:

  1. Crea una copia della prenotazione come prenotazione con target specifico per una singola istanza.

  2. Crea un'istanza di test per consumare la prenotazione.

Se riesci a creare l'istanza di test, le sue proprietà corrispondono a quelle della prenotazione di test. In caso contrario, si verificano degli errori.

Dopo aver verificato che le proprietà dell'istanza di test e della prenotazione di test coincidono, elimina la prenotazione e l'istanza di test.

Verifica il consumo delle prenotazioni

Per verificare il consumo delle prenotazioni, puoi eseguire una o più delle seguenti operazioni:

  • Per visualizzare il numero corrente di istanze di computing che stanno consumando le tue prenotazioni e quante altre istanze possono consumarle, visualizza le prenotazioni.

  • Per monitorare i dati sul consumo delle prenotazioni aggiornati ogni 30 minuti e ricevere avvisi quando queste vengono consumate o meno, monitora il consumo delle prenotazioni.

  • Per visualizzare i dati sul consumo delle prenotazioni aggiornati ogni 24 ore, esegui una delle seguenti operazioni:

Passaggi successivi