创建使用抢占式虚拟机的 MIG


本文档介绍如何创建使用抢占式虚拟机 (VM) 实例的代管式实例组 (MIG)。如果您的工作负载可以容忍中断,并且您希望利用与抢占式虚拟机相关的费用节省,则抢占式虚拟机非常有用。

您还可以阅读创建 MIG 的其他基本场景

准备工作

  • 设置身份验证(如果尚未设置)。身份验证是通过其进行身份验证以访问 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. 安装 Google Cloud CLI,然后通过运行以下命令初始化 Google Cloud CLI:

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

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

      1. 安装 Google Cloud CLI。
      2. 如需初始化 gcloud CLI,请运行以下命令:

        gcloud init
      3. 为您的 Google 账号创建本地身份验证凭据:

        gcloud auth application-default login

      如需了解详情,请参阅 Set up authentication for a local development environment

      REST

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

        安装 Google Cloud CLI,然后通过运行以下命令初始化 Google Cloud CLI:

        gcloud init

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

限制

如需查看 MIG 限制的完整列表(因您使用的配置而异),请参阅 MIG 限制

创建使用抢占式虚拟机的实例模板

您可以使用可用区级或区域级 MIG 快速创建多个抢占式虚拟机,这样可以降低代管式实例组中虚拟机的费用。例如,您可以创建一组抢占式虚拟机,使用这些虚拟机运行批处理任务,然后在任务完成时删除该组。

如需创建一组抢占式虚拟机,请在实例模板中设置抢占式选项,然后使用该模板创建 MIG。

控制台

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

    转到“实例模板”

    其余步骤将自动显示在 Google Cloud 控制台中。

  2. 点击创建实例模板
  3. 根据需要为您的实例模板填写属性。
  4. 点击高级选项,然后展开管理部分。
  5. 可用性政策下的 VM provision model(虚拟机预配模型)列表中,选择 Spot
  6. 点击创建以创建模板。

gcloud

使用 instance-templates create 命令创建实例模板。添加 --preemptible 标志。

gcloud compute instance-templates create INSTANCE_TEMPLATE \
    --preemptible

Terraform

以下示例会创建一个全球级实例模板。如需提供抢占式选项,请添加 scheduling 块。如需详细了解示例中使用的资源,请参阅 google_compute_instance_template 资源。如需创建区域级实例模板,请使用 google_compute_region_instance_template 资源

resource "google_compute_instance_template" "default" {
  name         = "preemptible-template"
  machine_type = "n1-standard-1"
  disk {
    source_image = "debian-cloud/debian-11"
  }
  network_interface {
    network = "default"
  }
  scheduling {
    preemptible       = "true"
    automatic_restart = "false"
  }
}

如需了解如何应用或移除 Terraform 配置,请参阅基本 Terraform 命令

REST

调用 instanceTemplates.insert 方法以创建一个新的实例模板。添加 scheduling.preemptible 属性并将其设为 true

{
"name": "INSTANCE_TEMPLATE",
"properties": {
  "machineType": "zones/ZONE/machineTypes/MACHINE_TYPE",
  "networkInterfaces": [
    {
      "network": "global/networks/default",
      "accessConfigs":
      [
        {
          "name": "external-IP",
          "type": "ONE_TO_ONE_NAT"
        }
      ]
    }
  ],
  "scheduling":
  {
    "preemptible": true
  },
  "disks":
  [
    {
      "type": "PERSISTENT",
      "boot": true,
      "mode": "READ_WRITE",
      "initializeParams":
      {
        "sourceImage": "projects/debian-cloud/global/images/family/debian-9"
      }
    }
  ]
  }
}

创建实例模板后,使用该模板创建 MIG,其中的虚拟机受限于单个可用区虚拟机分布在一个区域中的多个可用区之间

后续步骤