Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En este documento, se describe cómo crear un grupo de instancias administrado (MIG) que use instancias de máquinas virtuales (VM) interrumpibles.
Las VM interrumpibles son útiles si tu carga de trabajo puede tolerar interrupciones y deseas aprovechar los ahorros de costos asociados con las VM interrumpibles.
Si aún no lo hiciste, configura la autenticación.
La autenticación verifica tu identidad para acceder a los Google Cloud servicios y las APIs. Para ejecutar código o muestras desde un entorno de desarrollo local, puedes autenticarte en Compute Engine seleccionando una de las siguientes opciones:
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
Instala Google Cloud CLI.
Después de la instalación,
inicializa Google Cloud CLI ejecutando el siguiente comando:
Para usar las muestras de Terraform de esta página en un entorno de desarrollo local, instala e
inicializa gcloud CLI y, luego, configura las credenciales predeterminadas de la aplicación con tus
credenciales de usuario.
Para obtener más información, consulta
Autentícate para usar REST
en la documentación de autenticación de Google Cloud .
Limitaciones
Para ver la lista completa de limitaciones del MIG, que varía según la configuración que uses, consulta Limitaciones del MIG.
Crea una plantilla de instancias con VMs interrumpibles
Puedes usar un MIG zonal o regional para crear con rapidez VMs interrumpibles, lo que puede reducir los costos de las VM en tus grupos de instancias administrados. Por ejemplo, puedes crear un grupo de VM interrumpibles, usarlo para ejecutar una tarea de procesamiento por lotes y, luego, borrar el grupo cuando se complete la tarea.
Para crear un grupo de VM interrumpibles, configura la opción interrumpible en una plantilla de instancias y, luego, usa la plantilla para crear el MIG.
Permisos necesarios para esta tarea
Para realizar esta tarea, debes tener los siguientes permisos:
En el siguiente ejemplo, se crea una plantilla de instancias global. Para proporcionar la opción interrumpible, incluye el bloque scheduling.
Para obtener más información sobre el recurso usado en la muestra, consulta recurso google_compute_instance_template. Para crear una plantilla de instancias regional, usa el recurso google_compute_region_instance_template.
Si deseas obtener más información para aplicar o quitar una configuración de Terraform, consulta los comandos básicos de Terraform.
REST
Llama al
método instanceTemplates.insert
para crear una plantilla de instancias nueva. Incluye la propiedad scheduling.preemptible
y configúrala como true.
Obtén información sobre cómo aplicar una configuración nueva a todas las VMs de un MIG o a un subconjunto de ellas mediante la configuración y la aplicación de una plantilla de instancias nueva, la configuración de todas las instancias, o la configuración por instancia.
Conserva discos, metadatos y direcciones IP en eventos disruptivos, como la recreación, la reparación automática y las actualizaciones de VM agregando una configuración con estado.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-04 (UTC)"],[[["\u003cp\u003eThis document outlines how to create a managed instance group (MIG) utilizing preemptible virtual machine (VM) instances to reduce costs for workloads that can tolerate disruptions.\u003c/p\u003e\n"],["\u003cp\u003ePreemptible VMs can be configured in an instance template, which is then used to create a MIG, either for zonal or regional deployment.\u003c/p\u003e\n"],["\u003cp\u003eAuthentication is required to access Google Cloud services and APIs, and can be set up through the Google Cloud console, gcloud CLI, Terraform, or REST API.\u003c/p\u003e\n"],["\u003cp\u003eCreating a preemptible instance template involves setting the "preemptible" option to "true" in the template's configuration, which can be done via the console, gcloud CLI, Terraform, or REST.\u003c/p\u003e\n"],["\u003cp\u003eAfter creating an instance template, you can further configure the MIG with features such as application-based autohealing, autoscaling, and stateful configurations, in addition to managing individual instances.\u003c/p\u003e\n"]]],[],null,["# Create a MIG that uses preemptible VMs\n\n*** ** * ** ***\n\nThis document describes how to create a\n[managed instance group (MIG)](/compute/docs/instance-groups#managed_instance_groups)\nthat uses preemptible virtual machine (VM) instances.\n[Preemptible VMs](/compute/docs/instances/preemptible) are useful if your\nworkload can tolerate disruptions and you want to take advantage of the\ncost-savings associated with preemptible VMs.\n\nYou can also read about other\n[basic scenarios for creating a MIG](/compute/docs/instance-groups/creating-groups-of-managed-instances#create_managed_group).\n\nBefore you begin\n----------------\n\n- If you haven't already, set up [authentication](/compute/docs/authentication). Authentication verifies your identity for access to Google Cloud services and APIs. To run code or samples from a local development environment, you can authenticate to Compute Engine by selecting one of the following options:\n\n Select the tab for how you plan to use the samples on this page: \n\n ### Console\n\n\n When you use the Google Cloud console to access Google Cloud services and\n APIs, you don't need to set up authentication.\n\n ### gcloud\n\n 1.\n [Install](/sdk/docs/install) the Google Cloud CLI.\n\n After installation,\n [initialize](/sdk/docs/initializing) the Google Cloud CLI by running the following command:\n\n ```bash\n gcloud init\n ```\n\n\n If you're using an external identity provider (IdP), you must first\n [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n | **Note:** If you installed the gcloud CLI previously, make sure you have the latest version by running `gcloud components update`.\n 2. [Set a default region and zone](/compute/docs/gcloud-compute#set_default_zone_and_region_in_your_local_client).\n\n ### Terraform\n\n\n To use the Terraform samples on this page in a local development environment, install and\n initialize the gcloud CLI, and then set up Application Default Credentials with your\n user credentials.\n 1. [Install](/sdk/docs/install) the Google Cloud CLI.\n 2. If you're using an external identity provider (IdP), you must first [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n | **Note:** If you installed the gcloud CLI previously, make sure you have the latest version by running `gcloud components update`.\n 3. If you're using a local shell, then create local authentication credentials for your user account: \n\n ```bash\n gcloud auth application-default login\n ```\n 4. You don't need to do this if you're using Cloud Shell.\n 5. 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](/iam/docs/workforce-log-in-gcloud).\n\n\n For more information, see\n [Set up authentication for a local development environment](/compute/docs/authentication#local-development).\n\n ### REST\n\n\n To use the REST API samples on this page in a local development environment, you use the\n credentials you provide to the gcloud CLI.\n 1. [Install](/sdk/docs/install) the Google Cloud CLI.\n 2. If you're using an external identity provider (IdP), you must first [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n\n For more information, see\n [Authenticate for using REST](/docs/authentication/rest)\n in the Google Cloud authentication documentation.\n\nLimitations\n-----------\n\nTo see the full list of MIG limitations, which varies based on the configuration\nthat you use, see\n[MIG limitations](/compute/docs/instance-groups/creating-groups-of-managed-instances#limitations).\n\nCreate an instance template with preemptible VMs\n------------------------------------------------\n\nYou can use a zonal or regional MIG to quickly create multiple\n[preemptible VMs](/compute/docs/instances/preemptible), which can reduce\nthe costs of the VMs in your managed instance groups. For example, you\ncan create a group of preemptible VMs, use them to run a batch processing\ntask, and then delete the group when the task is complete.\n\nTo create a group of preemptible VMs, set the preemptible option in an\n[instance template](/compute/docs/instance-templates), and then use the template\nto create the MIG.\n\n#### Permissions required for this task\n\nTo perform this task, you must have the following\n[permissions](/iam/docs/overview#permissions):\n\n\n- All permissions required to [create a new instance](/compute/docs/instances/create-start-instance)\n- `compute.instanceTemplates.use` on the instance template \n\n### Console\n\n1. In the console, go to the **Instance templates** page.\n\n [Go to Instance templates](https://console.cloud.google.com/compute/instanceTemplates?walkthrough_id=compute--instance-groups--create-mig-preemptible-vms&start_index=1#step_index=1)\n\n The remaining steps appear in the Google Cloud console.\n2. Click **Create instance template**.\n3. Fill in the properties that you want for your instance template.\n4. Click **Advanced options** and expand the **Management** section.\n5. Under **Availability policy** , in the **VM provision model** list, choose **Spot**.\n6. Click **Create** to create the template.\n\n### gcloud\n\nCreate an instance template by using the\n[`instance-templates create` command](/sdk/gcloud/reference/compute/instance-templates/create).\nInclude the `--preemptible` flag. \n\n```\ngcloud compute instance-templates create INSTANCE_TEMPLATE \\\n --preemptible\n```\n\n### Terraform\n\nThe following sample creates a global instance template. To provide the\npreemptible option, include the `scheduling` block.\nFor more information about the resource used in the sample, see\n[`google_compute_instance_template` resource](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_instance_template). To create a regional instance\ntemplate, use the [`google_compute_region_instance_template` resource](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_region_instance_template). \n\n resource \"google_compute_instance_template\" \"default\" {\n name = \"preemptible-template\"\n machine_type = \"n1-standard-1\"\n disk {\n source_image = \"debian-cloud/debian-11\"\n }\n network_interface {\n network = \"default\"\n }\n scheduling {\n preemptible = \"true\"\n automatic_restart = \"false\"\n }\n }\n\nTo learn how to apply or remove a Terraform configuration, see\n[Basic Terraform commands](/docs/terraform/basic-commands).\n\n### REST\n\nCall the\n[`instanceTemplates.insert` method](/compute/docs/reference/latest/instanceTemplates/insert)\nto create a new instance template. Include the `scheduling.preemptible`\nproperty and set it to `true`. \n\n```\n{\n\"name\": \"INSTANCE_TEMPLATE\",\n\"properties\": {\n \"machineType\": \"zones/ZONE/machineTypes/MACHINE_TYPE\",\n \"networkInterfaces\": [\n {\n \"network\": \"global/networks/default\",\n \"accessConfigs\":\n [\n {\n \"name\": \"external-IP\",\n \"type\": \"ONE_TO_ONE_NAT\"\n }\n ]\n }\n ],\n \"scheduling\":\n {\n \"preemptible\": true\n },\n \"disks\":\n [\n {\n \"type\": \"PERSISTENT\",\n \"boot\": true,\n \"mode\": \"READ_WRITE\",\n \"initializeParams\":\n {\n \"sourceImage\": \"projects/debian-cloud/global/images/family/debian-9\"\n }\n }\n ]\n }\n}\n```\n\nAfter you create the instance template, use it to create a MIG\n[with VMs confined to a single zone](/compute/docs/instance-groups/create-zonal-mig)\nor\n[with VMs spread across multiple zones in a region](/compute/docs/instance-groups/distributing-instances-with-regional-instance-groups).\n\nWhat's next\n-----------\n\n- [Set up application-based autohealing](/compute/docs/instance-groups/autohealing-instances-in-migs), which periodically verifies that your application responds as expected on each of the MIG's VMs and automatically recreates unresponsive VMs.\n- [Enable autoscaling](/compute/docs/autoscaler) to automatically add or delete VMs from your MIG based on increases or decreases in load.\n- Learn how to [apply a new configuration](/compute/docs/instance-groups/updating-migs) to all or to a subset of the VMs in a MIG by setting and applying a new instance template, all-instances configuration, or per-instance configuration.\n- Preserve disks, metadata, and IP addresses across disruptive events like VM recreation, autohealing, and updates by [adding stateful configuration](/compute/docs/instance-groups/configuring-stateful-migs).\n- Learn about [working with managed instances](/compute/docs/instance-groups/working-with-managed-instances), for example, to delete, abandon, and recreate VMs in a MIG.\n- [View info](/compute/docs/instance-groups/getting-info-about-migs) about MIGs and their VMs."]]