Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Neste documento, você verá como criar um grupo de instâncias gerenciadas (MIG) que usa instâncias de máquina virtual preemptiva (VM).
As VMs preemptivas são úteis se a
carga de trabalho puder tolerar interrupções e você quiser aproveitar a
economia associada às VMs preemptivas.
Configure a autenticação, caso ainda não tenha feito isso.
A autenticação é
o processo de verificação da sua identidade para acesso a serviços e APIs do Google Cloud .
Para executar códigos ou amostras de um ambiente de desenvolvimento local, autentique-se no
Compute Engine selecionando uma das seguintes opções:
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
Instale a CLI do Google Cloud.
Após a instalação,
inicialize a Google Cloud CLI executando o seguinte comando:
Para usar os exemplos do Terraform nesta página em um ambiente de desenvolvimento local, instale e
inicialize a CLI gcloud e configure o Application Default Credentials com suas
credenciais de usuário.
Para mais informações, consulte
Autenticar para usar REST
na documentação de autenticação do Google Cloud .
Limitações
Para ver a lista completa de limitações do MIG, que varia de acordo com a configuração
usada, consulte
Limitações do MIG.
Criar um modelo de instância com as VMs preemptivas
Use um MIG zonal ou regional para criar rapidamente várias
VMs preemptivas, o que pode reduzir
os custos das VMs nos grupos de instâncias gerenciadas. Por exemplo, crie um grupo de VMs preemptivas, use-o para executar uma tarefa de processamento em lote e depois exclua-o quando a tarefa estiver concluída.
Para criar um grupo de VMs preemptivas, defina a opção preemptiva em um modelo de instância e depois use o modelo para criar o MIG.
Permissões exigidas para a tarefa
Para executar esta tarefa, é necessário ter as seguintes
permissões:
Ative o escalonamento automático para adicionar ou excluir VMs automaticamente do seu MIG com base em aumentos ou reduções de carga.
Saiba como aplicar uma nova configuração
a todas ou a um subconjunto das VMs em um MIG definindo e aplicando um novo
modelo de instância, configuração de todas as instâncias ou configuração por instância.
Preserve discos, metadados e endereços IP em eventos que causam interrupções, como recriação
de VM, recuperação automática e atualizações por meio da
configuração com estado.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-19 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."]]