本文档介绍如何创建使用抢占式虚拟机 (VM) 实例的代管式实例组 (MIG)。如果您的工作负载可以容忍中断,并且您希望利用与抢占式虚拟机相关的费用节省,则抢占式虚拟机非常有用。
您还可以阅读创建 MIG 的其他基本场景。
准备工作
-
设置身份验证(如果尚未设置)。身份验证是通过其进行身份验证以访问 Google Cloud 服务和 API 的过程。如需从本地开发环境运行代码或示例,您可以按如下方式向 Compute Engine 进行身份验证。
Select the tab for how you plan to use the samples on this page:
When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.
-
Install the Google Cloud CLI, then initialize it by running the following command:
gcloud init
- Set a default region and zone.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
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.
Terraform
如需在本地开发环境中使用本页面上的 Terraform 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。
如需了解详情,请参阅 Set up authentication for a local development environment。
REST
如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 gcloud CLI 的凭据。
Install the Google Cloud CLI, then initialize it by running the following command:
gcloud init
如需了解详情,请参阅 Google Cloud 身份验证文档中的使用 REST 时进行身份验证。
-
限制
如需查看 MIG 限制的完整列表(因您使用的配置而异),请参阅 MIG 限制。
创建使用抢占式虚拟机的实例模板
您可以使用可用区级或区域级 MIG 快速创建多个抢占式虚拟机,这样可以降低代管式实例组中虚拟机的费用。例如,您可以创建一组抢占式虚拟机,使用这些虚拟机运行批处理任务,然后在任务完成时删除该组。
如需创建一组抢占式虚拟机,请在实例模板中设置抢占式选项,然后使用该模板创建 MIG。
执行此任务所需的权限
您必须拥有以下权限才能执行此任务:
- 创建新实例所需的所有权限
- 针对实例模板的
compute.instanceTemplates.use
权限
-
在控制台中,转到实例模板页面。
其余步骤会显示在 Google Cloud 控制台中。
-
点击
创建实例模板 。 - 根据需要为您的实例模板填写属性。
-
点击
高级选项 ,然后展开管理部分。 -
在可用性政策下的
VM provision model (虚拟机预配模型)列表中,选择 Spot。 -
点击
创建 以创建模板。
使用 instance-templates create
命令创建实例模板。添加 --preemptible
标志。
gcloud compute instance-templates createINSTANCE_TEMPLATE \ --preemptible
以下示例会创建一个全球级实例模板。如需提供抢占式选项,请添加 scheduling
块。如需详细了解示例中使用的资源,请参阅 google_compute_instance_template
资源。如需创建区域级实例模板,请使用 google_compute_region_instance_template
资源。
如需了解如何应用或移除 Terraform 配置,请参阅基本 Terraform 命令。
调用 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,其中的虚拟机受限于单个可用区或虚拟机分布在一个区域中的多个可用区之间。
后续步骤
- 设置基于应用的自动修复功能,该功能会定期验证应用是否在 MIG 的每个虚拟机上按预期响应,并自动重新创建无响应的虚拟机。
- 启用自动扩缩功能,以根据负载的增减自动在 MIG 中添加或删除虚拟机。
- 了解如何通过设置并应用新的实例模板、所有实例配置或每个实例配置,将新配置应用于 MIG 中的所有或部分虚拟机。
- 通过添加有状态配置,在虚拟机重新创建、自动修复和更新等破坏性事件中保留磁盘、元数据和 IP 地址。
- 了解如何使用代管式实例,例如,如何删除、放弃和重新创建 MIG 中的虚拟机。
- 查看有关 MIG 及其虚拟机的信息。