阻止计算实例使用预留


本文档介绍了如何阻止 Compute Engine 实例使用预留资源。如需详细了解预留,请参阅 Compute Engine 可用区级资源的预留

自动使用的预留允许属性与预留匹配的实例自动使用这些预留。如需阻止实例使用预留,请执行以下操作之一:

  • 按照本文档中的说明配置实例以不使用预留。

  • 创建或更新的具有与预留不匹配的属性的实例。

当您要将实例用于测试、调试或隔离部署等任务时,可以避免消耗预留。

限制

只有当实例配置为自动使用匹配的预留时,您才能将现有实例更新为不使用预留。

准备工作

  • 如果您尚未设置身份验证,请进行设置。身份验证是通过其进行身份验证以访问 Google Cloud 服务和 API 的过程。如需从本地开发环境运行代码或示例,您可以通过选择以下选项之一向 Compute Engine 进行身份验证:

    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. Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init
    2. Set a default region and zone.
    3. Go

      如需在本地开发环境中使用本页面上的 Go 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      如需了解详情,请参阅 Set up authentication for a local development environment。 如需了解详情,请参阅身份验证文档中的为本地开发环境设置 ADC

      Java

      如需在本地开发环境中使用本页面上的 Java 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      如需了解详情,请参阅 Set up authentication for a local development environment。 如需了解详情,请参阅身份验证文档中的为本地开发环境设置 ADC

      Node.js

      如需在本地开发环境中使用本页面上的 Node.js 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      如需了解详情,请参阅 Set up authentication for a local development environment。 如需了解详情,请参阅身份验证文档中的为本地开发环境设置 ADC

      Python

      如需在本地开发环境中使用本页面上的 Python 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      如需了解详情,请参阅 Set up authentication for a local development environment。 如需了解详情,请参阅身份验证文档中的为本地开发环境设置 ADC

      REST

      如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 gcloud CLI 的凭据。

        Install the Google Cloud CLI, then initialize it by running the following command:

        gcloud init

      如需了解详情,请参阅 Google Cloud 身份验证文档中的使用 REST 时进行身份验证

所需的角色

如需获得阻止计算实例使用预留所需的权限,请让管理员为您授予项目的 Compute Instance Admin (v1) (roles/compute.instanceAdmin.v1) IAM 角色。 如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

此预定义角色包含阻止计算实例使用预留所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

若要阻止计算实例使用预留,您需要具备以下权限:

  • 创建预留:项目的 compute.reservations.create 权限
  • 如需创建实例,请执行以下操作:
    • 针对项目的 compute.instances.create 权限
    • 使用自定义映像创建虚拟机:针对映像的 compute.images.useReadOnly 权限
    • 使用快照创建虚拟机:针对快照的 compute.snapshots.useReadOnly 权限
    • 使用实例模板创建虚拟机:针对实例模板的 compute.instanceTemplates.useReadOnly 权限
    • 为虚拟机分配旧版网络:针对项目的 compute.networks.use 权限
    • 为虚拟机指定静态 IP 地址:针对项目的 compute.addresses.use 权限
    • 使用旧版网络时为虚拟机分配外部 IP 地址:针对项目的 compute.networks.useExternalIp 权限
    • 为虚拟机指定子网:针对项目或所选子网的 compute.subnetworks.use 权限
    • 在使用 VPC 网络时为虚拟机分配外部 IP 地址:针对项目或所选子网的 compute.subnetworks.useExternalIp 权限
    • 为虚拟机设置虚拟机实例元数据:针对项目的 compute.instances.setMetadata 权限
    • 为虚拟机设置标记:针对虚拟机的 compute.instances.setTags 权限
    • 为虚拟机设置标签:针对虚拟机的 compute.instances.setLabels 权限
    • 为虚拟机设置要使用的服务账号:针对虚拟机的 compute.instances.setServiceAccount 权限
    • 为虚拟机创建新磁盘:针对项目的 compute.disks.create 权限
    • 以只读或读写模式挂接现有磁盘:针对磁盘的 compute.disks.use 权限
    • 以只读模式挂接现有磁盘:针对磁盘的 compute.disks.useReadOnly 权限
  • 创建实例模板:针对项目的 compute.instanceTemplates.create 权限

您也可以使用自定义角色或其他预定义角色来获取这些权限。

防止预留消耗

如需阻止计算实例使用预留,请将其预留亲和性 (reservationAffinity) 属性设置为不使用预留。此属性用于控制实例能否使用匹配的预留、特定的预留或任何预留。

如需阻止一个或多个实例使用预留,请使用以下任一方法:

阻止在现有实例中使用

您可以更新正在运行的实例,使其不再自动消耗预订。您必须重启实例,才能使更改生效,如本部分所述。

如需阻止现有实例使用预留,请选择以下选项之一:

gcloud

  1. 创建一个空的 YAML 文件。

  2. 如需将实例的属性导出到您刚创建的 YAML 文件中,请使用 gcloud compute instances export 命令

    gcloud compute instances export INSTANCE_NAME \
        --destination=YAML_FILE \
        --zone=ZONE
    

    替换以下内容:

    • INSTANCE_NAME:实例的名称。

    • YAML_FILE:您在上一步中创建的空 YAML 文件的路径。

    • ZONE:实例所在的可用区。

  3. 在 YAML 配置文件中,将 consumeReservationType 设置为 NO_RESERVATION

    reservationAffinity:
      consumeReservationType: NO_RESERVATION
    
  4. 如需更新实例并重启它,请使用 gcloud compute instances update-from-file 命令,并将 --most-disruptive-allowed-action 标志设置为 RESTART

    gcloud compute instances update-from-file INSTANCE_NAME \
        --most-disruptive-allowed-action=RESTART \
        --source=YAML_FILE \
        --zone=ZONE
    

    替换以下内容:

    • INSTANCE_NAME:实例的名称。

    • YAML_FILE:包含您在上一步中修改的配置数据的 YAML 文件的路径。

    • ZONE:实例所在的可用区。

REST

  1. 如需查看现有实例的属性,请向 instances.get 方法发出 GET 请求:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME
    

    替换以下内容:

    • PROJECT_ID:您在其中创建了实例的项目的 ID。

    • ZONE:实例所在的可用区。

    • INSTANCE_NAME:实例的名称。

  2. GET 请求的输出存储在文件或文本编辑器中。修改复制的输出,将 consumeReservationType 字段更改为 NO_RESERVATION

    {
      ...
      "reservationAffinity": {
        "consumeReservationType": "NO_RESERVATION"
      },
      ...
    }
    
  3. 如需更新实例并重启它,请向 instances.update 方法发出 PUT 请求。在请求中,执行以下操作:

    • 在请求网址中添加 mostDisruptiveAllowedAction 查询参数并设置为 RESTART

    • 对于请求正文,请使用您在上一步中修改的 GET 请求的输出。

    请求类似于以下示例:

    PUT https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central-1/instances/instance-01?mostDisruptiveAllowedAction=RESTART
    
    {
      ...
      "reservationAffinity": {
        "consumeReservationType": "NO_RESERVATION"
      },
      ...
    }
    

如需详细了解如何更新实例,请参阅更新实例属性

在创建实例时防止消耗

如需创建无法使用预留的计算实例,请选择以下选项之一:

控制台

  1. 在 Google Cloud 控制台中,转到创建实例页面。

    打开“创建实例”

  2. 名称字段中,输入实例的名称。

  3. 区域可用区列表中,选择要在其中创建实例的区域和可用区。

  4. 指定要用于实例的机器类型。

  5. 在导航菜单中,点击高级

  6. 预留部分,选择不使用预留

  7. 点击创建

gcloud

如需创建无法使用预留的实例,请将 gcloud compute instances create 命令--reservation-affinity 标志设为 none

gcloud compute instances create INSTANCE_NAME \
    --machine-type=MACHINE_TYPE \
    --reservation-affinity=none \
    --zone=ZONE

替换以下内容:

  • INSTANCE_NAME:实例的名称。

  • MACHINE_TYPE:要用于实例的机器类型。

  • ZONE:要在其中创建实例的区域。

Go

如需创建无法使用预留实例的虚拟机,请使用以下代码示例:

import (
	"context"
	"fmt"
	"io"

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

// createInstanceNotConsumeReservation creates VM, without consuming reservation
func createInstanceNotConsumeReservation(w io.Writer, projectID, zone, instanceName string) error {
	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"),
				},
			},
			ReservationAffinity: &computepb.ReservationAffinity{
				ConsumeReservationType: proto.String("NO_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\n")

	return nil
}

Java

如需创建无法使用预留实例的虚拟机,请使用以下代码示例:

import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.NO_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 CreateInstanceWithoutConsumingReservation {
  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 you want to use.
    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.
    // *   This value uses the format zones/{zone}/machineTypes/{type_name}.
    // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
    String machineTypeName = "n1-standard-1";
    // 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";

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

  // Create a virtual machine that explicitly doesn't consume reservations
  public static Instance createInstanceWithoutConsumingReservationAsync(
      String project, String zone, String instanceName,
      String machineTypeName, String sourceImage, long diskSizeGb, String networkName)
      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(NO_RESERVATION.toString())
              .build();

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

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

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

      // Wait for the operation to complete.
      Operation response = operation.get(3, TimeUnit.MINUTES);

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

Node.js

如需创建无法使用预留实例的虚拟机,请使用以下代码示例:

// 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 a VM that explicitly doesn't consume reservations
async function callCreateInstanceToNotConsumeReservation() {
  // 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: 'NO_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 callCreateInstanceToNotConsumeReservation();

Python

如需创建无法使用预留实例的虚拟机,请使用以下代码示例:

from __future__ import annotations

import sys
from typing import Any

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


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

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

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

    Returns:
        Whatever the operation.result() returns.

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

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

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

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

    return result


def create_vm_not_consume_reservation(
    project_id: str, zone: str, instance_name: str, machine_type: str = "n2-standard-2"
) -> compute_v1.Instance:
    """Creates a VM that explicitly doesn't consume reservations
    Args:
        project_id (str): The ID of the Google Cloud project.
        zone (str): The zone where the VM will be created.
        instance_name (str): The name of the instance to create.
        machine_type (str, optional): The machine type for the instance.
    Returns:
        compute_v1.Instance: The created instance.
    """
    instance = compute_v1.Instance()
    instance.name = instance_name
    instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
    instance.zone = zone

    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
                )
            ],
        )
    ]

    # Set the reservation affinity to not consume any reservation
    instance.reservation_affinity = compute_v1.ReservationAffinity(
        consume_reservation_type="NO_RESERVATION",  # Prevents the instance from consuming reservations
    )

    # 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"Creating the {instance_name} instance in {zone}...")

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

REST

如需创建无法使用预留的实例,请向 instances.insert 方法发出 POST 请求。在请求正文中,添加设置为 NO_RESERVATIONconsumeReservationType 字段:

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

{
  "name": "INSTANCE_NAME",
  "machineType": "zones/ZONE/machineTypes/MACHINE_TYPE",
  "disks": [
    {
      "boot": true,
      "initializeParams": {
        "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"
      }
    }
  ],
  "networkInterfaces": [
    {
      "network": "global/networks/default"
    }
  ],
  "reservationAffinity": {
    "consumeReservationType": "NO_RESERVATION"
  }
}

替换以下内容:

  • PROJECT_ID:您要在其中创建实例的项目的 ID。

  • ZONE:要在其中创建实例的区域。

  • INSTANCE_NAME:实例的名称。

  • MACHINE_TYPE:要用于实例的机器类型。

  • IMAGE_PROJECT:操作系统映像所属的映像项目;例如 debian-cloud。如需详细了解支持的映像项目,请参阅公共映像

  • IMAGE:指定以下其中一项:

    • 操作系统映像的特定版本;例如 debian-12-bookworm-v20240617

    • 映像系列,其格式必须为 family/IMAGE_FAMILY。此项指定最新的未弃用操作系统映像。例如,如果您指定 family/debian-12,则系统会使用 Debian 12 映像系列中的最新版本。如需详细了解如何使用映像系列,请参阅映像系列最佳实践

如需详细了解如何创建实例,请参阅创建和启动 Compute Engine 实例

防止在批量创建实例时发生消耗

如需批量创建无法使用预留的计算实例,请选择以下选项之一:

gcloud

如需批量创建无法使用预留的实例,请使用 gcloud compute instances bulk create 命令,并将 --reservation-affinity 标志设置为 none

例如,如需在单个可用区中批量创建实例并指定名称模式,请运行以下命令:

gcloud compute instances bulk create \
    --count=COUNT \
    --machine-type=MACHINE_TYPE \
    --name-pattern="NAME_PATTERN" \
    --reservation-affinity=none \
    --zone=ZONE

替换以下内容:

  • COUNT:要创建的实例数量。

  • MACHINE_TYPE:要用于实例的机器类型。

  • NAME_PATTERN:实例的名称模式。如需替换实例名称中的数字序列,请使用哈希值 (#) 字符序列。例如,使用 instance-# 作为名称模式将生成名称以 instance-1instance-2 开头的实例,一直到由 COUNT 指定的实例数量。

  • ZONE:要用于批量创建实例的可用区。

REST

如需批量创建无法使用预留的实例,请向 instances.bulkInsert 方法发出 POST 请求。在请求正文中,添加设置为 NO_RESERVATIONconsumeReservationType 字段。

例如,如需在单个可用区中批量创建实例并指定名称模式,请发出以下请求:

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

{
  "count": COUNT,
  "namePattern": "NAME_PATTERN",
  "instanceProperties": {
    "machineType": "MACHINE_TYPE",
    "disks": [
      {
        "boot": true,
        "initializeParams": {
          "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"
        }
      }
    ],
    "networkInterfaces": [
      {
        "network": "global/networks/default"
      }
    ],
    "reservationAffinity": {
      "consumeReservationType": "NO_RESERVATION"
    }
  }
}

替换以下内容:

  • PROJECT_ID:要在其中批量创建实例的项目的 ID。

  • ZONE:要用于批量创建实例的可用区。

  • COUNT:要创建的实例数量。

  • NAME_PATTERN:实例的名称模式。如需替换实例名称中的数字序列,请使用哈希值 (#) 字符序列。例如,使用 instance-# 作为名称模式将生成名称以 instance-1instance-2 开头的实例,一直到由 COUNT 指定的实例数量。

  • MACHINE_TYPE:要用于实例的机器类型。

  • IMAGE_PROJECT:操作系统映像所属的映像项目;例如 debian-cloud。如需详细了解支持的映像项目,请参阅公共映像

  • IMAGE:指定以下其中一项:

    • 操作系统映像的特定版本;例如 debian-12-bookworm-v20240617

    • 映像系列,其格式必须为 family/IMAGE_FAMILY。此项指定最新的未弃用操作系统映像。例如,如果您指定 family/debian-12,则系统会使用 Debian 12 映像系列中的最新版本。如需详细了解如何使用映像系列,请参阅映像系列最佳实践

如需详细了解如何批量创建实例,请参阅批量创建虚拟机

在创建实例模板时禁止使用

创建将实例配置为不使用预留的实例模板后,您可以使用该模板执行以下操作:

如需创建实例模板,以将实例配置为不使用预留,请选择以下选项之一:

控制台

  1. 在 Google Cloud 控制台中,前往创建实例模板页面。

    前往创建实例模板

  2. 名称字段中,输入实例模板的名称。

  3. 位置部分中,指定您要创建区域级(默认)实例模板还是全球实例模板。

  4. 机器配置部分中,指定要用于使用模板创建的实例的机器类型。

  5. 展开高级选项部分,然后执行以下操作:

    1. 展开管理部分。

    2. 预留部分,选择不使用预留

  6. 点击创建

gcloud

如需创建实例模板,以将实例配置为不使用预留,请使用 gcloud compute instances-templates create 命令,并将 --reservation-affinity 标志设置为 none

如需创建区域实例模板以将实例配置为不使用预留,请运行以下命令。如果您要创建全球实例模板,请使用不带 --instance-template-region 标志的相同命令。

gcloud compute instance-templates create INSTANCE_TEMPLATE_NAME \
    --instance-template-region=REGION \
    --machine-type=MACHINE_TYPE \
    --reservation-affinity=none

替换以下内容:

  • INSTANCE_TEMPLATE_NAME:实例模板的名称。

  • REGION:要在其中创建实例模板的区域。

  • MACHINE_TYPE:要用于使用实例模板创建的实例的机器类型。

Go

如需创建实例模板,以将实例配置为不使用预留,请使用以下代码示例:

import (
	"context"
	"fmt"
	"io"

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

// createInstanceNotConsumeReservation creates a new instance template, which won't consume reservations
func createTemplateNotConsumeReservation(w io.Writer, projectID, templateName string) error {
	// projectID := "your_project_id"
	// templateName := "your_template_name"

	ctx := context.Background()
	instanceTemplatesClient, err := compute.NewInstanceTemplatesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstanceTemplatesRESTClient: %w", err)
	}
	defer instanceTemplatesClient.Close()

	req := &computepb.InsertInstanceTemplateRequest{
		Project: projectID,
		InstanceTemplateResource: &computepb.InstanceTemplate{
			Name: proto.String(templateName),
			Properties: &computepb.InstanceProperties{
				// The template describes the size and source image of the boot disk
				// to attach to the instance.
				Disks: []*computepb.AttachedDisk{
					{
						InitializeParams: &computepb.AttachedDiskInitializeParams{
							DiskSizeGb:  proto.Int64(250),
							SourceImage: proto.String("projects/debian-cloud/global/images/family/debian-11"),
						},
						AutoDelete: proto.Bool(true),
						Boot:       proto.Bool(true),
					},
				},
				MachineType: proto.String("e2-standard-4"),
				// The template connects the instance to the `default` network,
				// without specifying a subnetwork.
				NetworkInterfaces: []*computepb.NetworkInterface{
					{
						Name: proto.String("global/networks/default"),
						// The template lets the instance use an external IP address.
						AccessConfigs: []*computepb.AccessConfig{
							{
								Name:        proto.String("External NAT"),
								Type:        proto.String(computepb.AccessConfig_ONE_TO_ONE_NAT.String()),
								NetworkTier: proto.String(computepb.AccessConfig_PREMIUM.String()),
							},
						},
					},
				},
				ReservationAffinity: &computepb.ReservationAffinity{
					ConsumeReservationType: proto.String("NO_RESERVATION"),
				},
			},
		},
	}

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

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

	fmt.Fprintf(w, "Instance template created\n")

	return nil
}

Java

如需创建实例模板,以将实例配置为不使用预留,请使用以下代码示例:

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

import com.google.cloud.compute.v1.AccessConfig;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.InsertInstanceTemplateRequest;
import com.google.cloud.compute.v1.InstanceProperties;
import com.google.cloud.compute.v1.InstanceTemplate;
import com.google.cloud.compute.v1.InstanceTemplatesClient;
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 CreateTemplateWithoutConsumingReservation {
  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 template you want to query.
    String templateName = "YOUR_INSTANCE_TEMPLATE_NAME";
    String machineType = "e2-standard-4";
    String sourceImage = "projects/debian-cloud/global/images/family/debian-11";

    createTemplateWithoutConsumingReservationAsync(
        projectId, templateName, machineType, sourceImage);
  }


  // Create a template that explicitly doesn't consume any reservations.
  public static InstanceTemplate createTemplateWithoutConsumingReservationAsync(
      String projectId, String templateName, String machineType, String sourceImage)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create()) {
      AttachedDisk attachedDisk = AttachedDisk.newBuilder()
          .setInitializeParams(AttachedDiskInitializeParams.newBuilder()
              .setSourceImage(sourceImage)
              .setDiskType("pd-balanced")
              .setDiskSizeGb(250)
              .build())
          .setAutoDelete(true)
          .setBoot(true)
          .build();

      NetworkInterface networkInterface = NetworkInterface.newBuilder()
          .setName("global/networks/default")
          .addAccessConfigs(AccessConfig.newBuilder()
              .setName("External NAT")
              .setType(AccessConfig.Type.ONE_TO_ONE_NAT.toString())
              .setNetworkTier(AccessConfig.NetworkTier.PREMIUM.toString())
              .build())
          .build();

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

      InstanceProperties instanceProperties = InstanceProperties.newBuilder()
          .addDisks(attachedDisk)
          .setMachineType(machineType)
          .setReservationAffinity(reservationAffinity)
          .addNetworkInterfaces(networkInterface)
          .build();

      InsertInstanceTemplateRequest insertInstanceTemplateRequest = InsertInstanceTemplateRequest
          .newBuilder()
          .setProject(projectId)
          .setInstanceTemplateResource(InstanceTemplate.newBuilder()
              .setName(templateName)
              .setProperties(instanceProperties)
              .build())
          .build();

      Operation response = instanceTemplatesClient.insertAsync(insertInstanceTemplateRequest)
          .get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        return null;
      }
      return instanceTemplatesClient.get(projectId, templateName);
    }
  }
}

Node.js

如需创建实例模板,以将实例配置为不使用预留,请使用以下代码示例:

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

// Instantiate an instanceTemplatesClient
const instanceTemplatesClient = new computeLib.InstanceTemplatesClient();
// Instantiate a globalOperationsClient
const globalOperationsClient = new computeLib.GlobalOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The ID of the project where you want to create template.
const projectId = await instanceTemplatesClient.getProjectId();
// The name of the template to create.
// const templateName = 'instance-01';

// Create an instance template that creates VMs that don't explicitly consume reservations
async function callCreateTemplateToNotConsumeReservation() {
  // Define the boot disk for the instance template
  const disk = new compute.AttachedDisk({
    initializeParams: new compute.AttachedDiskInitializeParams({
      sourceImage:
        'projects/debian-cloud/global/images/debian-12-bookworm-v20240815',
      diskSizeGb: '100',
      diskType: 'pd-balanced',
    }),
    autoDelete: true,
    boot: true,
    type: 'PERSISTENT',
  });

  // Define the network interface for the instance template
  const network = new compute.NetworkInterface({
    network: `projects/${projectId}/global/networks/default`,
  });

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

  // Define instance template
  const instanceTemplate = new compute.InstanceTemplate({
    name: templateName,
    properties: {
      disks: [disk],
      machineType: 'e2-medium',
      // The template connects the instance to the `default` network,
      // without specifying a subnetwork.
      networkInterfaces: [network],
      reservationAffinity,
    },
  });

  const [response] = await instanceTemplatesClient.insert({
    project: projectId,
    instanceTemplateResource: instanceTemplate,
  });

  let operation = response.latestResponse;

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

  console.log(`Template ${templateName} created.`);
}

await callCreateTemplateToNotConsumeReservation();

Python

如需创建实例模板,以将实例配置为不使用预留,请使用以下代码示例:

from __future__ import annotations

import sys
from typing import Any

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


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

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

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

    Returns:
        Whatever the operation.result() returns.

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

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

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

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

    return result


def create_instance_template_not_consume_reservation(
    project_id: str,
    template_name: str,
    machine_type: str = "n1-standard-1",
) -> compute_v1.InstanceTemplate:
    """
    Creates an instance template that creates VMs that don't explicitly consume reservations

    Args:
        project_id: project ID or project number of the Cloud project you use.
        template_name: name of the new template to create.
        machine_type: machine type for the instance.
    Returns:
        InstanceTemplate object that represents the new instance template.
    """

    template = compute_v1.InstanceTemplate()
    template.name = template_name
    template.properties.machine_type = machine_type
    # The template describes the size and source image of the boot disk
    # to attach to the instance.
    template.properties.disks = [
        compute_v1.AttachedDisk(
            boot=True,
            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,
            ),
        )
    ]
    # The template connects the instance to the `default` network,
    template.properties.network_interfaces = [
        compute_v1.NetworkInterface(
            network="global/networks/default",
            access_configs=[
                compute_v1.AccessConfig(
                    name="External NAT",
                    type="ONE_TO_ONE_NAT",
                )
            ],
        )
    ]
    # The template doesn't explicitly consume reservations
    template.properties.reservation_affinity = compute_v1.ReservationAffinity(
        consume_reservation_type="NO_RESERVATION"
    )

    template_client = compute_v1.InstanceTemplatesClient()
    operation = template_client.insert(
        project=project_id, instance_template_resource=template
    )

    wait_for_extended_operation(operation, "instance template creation")

    return template_client.get(project=project_id, instance_template=template_name)

REST

如需创建实例模板,以将实例配置为不使用预留,请向以下方法之一发出 POST 请求:

在请求正文中,添加 consumeReservationType 字段并将其设置为 NO_RESERVATION

例如,如需创建区域级实例模板并指定不使用预留,请发出以下请求:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/InstanceTemplates

{
  "name": "INSTANCE_TEMPLATE_NAME",
  "properties": {
    "machineType": "MACHINE_TYPE",
    "disks": [
      {
        "boot": true,
        "initializeParams": {
          "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"
        }
      }
    ],
    "networkInterfaces": [
      {
        "network": "global/networks/default"
      }
    ],
    "reservationAffinity": {
      "consumeReservationType": "NO_RESERVATION"
    }
  }
}

替换以下内容:

  • PROJECT_ID:要在其中创建实例模板的项目的 ID。

  • INSTANCE_TEMPLATE_NAME:实例模板的名称。

  • MACHINE_TYPE:要用于使用实例模板创建的实例的机器类型。

  • IMAGE_PROJECT:操作系统映像所属的映像项目;例如 debian-cloud。如需详细了解支持的映像项目,请参阅公共映像

  • IMAGE:指定以下其中一项:

    • 操作系统映像的特定版本;例如 debian-12-bookworm-v20240617

    • 映像系列,其格式必须为 family/IMAGE_FAMILY。此项指定最新的未弃用操作系统映像。例如,如果您指定 family/debian-12,则系统会使用 Debian 12 映像系列中的最新版本。如需详细了解如何使用映像系列,请参阅映像系列最佳实践

如需详细了解如何创建实例模板,请参阅创建实例模板

后续步骤