Limit the run time of VMs in a MIG

This document describes how to automatically terminate virtual machines (VMs)in a managed instance group (MIG) by specifying a time limit for the VMs. Italso describes how time limit works for VMs in a MIG.

You can optimize temporary workloads by specifying a time limit for the VMs in aMIG. When a VM reaches its time limit, the MIG automatically terminates(deletes) that VM. Limiting the run time of VMs in a MIG by a time limit helps tominimize costs and free up quota.

Note:GPU VMs that are configured to be automatically deletedafter a predefined run time of 7 days or less can consume either preemptible orstandard allocation quotas. This behavior is intendedto help you improve the obtainability of allocation quota fortemporary-but-uninterrupted workloads. For more information about thisbehavior, seeGPU VMs and preemptible allocation quotas.

To learn about specifying a time limit for a standalone VM, seeLimit the run time of a VM. If youwant a MIG to automatically add or delete VMs based on your workloads, seeAutoscaling groups of instances.

Before you begin

Limit the run time of VMs in a MIG

You can limit the run time of VMs in a MIG by specifying a time limit in theinstance template used forthe MIG. When the MIG creates VMs based on the template, thetime limit is applied to each VM.

You can specify one of two types of time limits:

  • Time limit as a run duration
  • Time limit as a termination time

To specify a time limit for the VMs in a MIG, follow these steps:

  1. Create an instance templatewith a run duration for VMs orwith a termination time for VMs.

  2. Use the instance template tocreate a MIGorupdate an existing MIG.

Limitations

Create an instance template with a run duration for VMs

To automatically terminate VMs in a MIG after they run for a certain duration,set a maximum run duration (maxRunDuration) in the instance template.

Console

  1. In the Google Cloud console, go to theInstance templates page.

    Go to Instance templates

  2. ClickCreate instance template.

  3. Select theLocation as follows:

    • If you want to use the instance template across regions,chooseGlobal.
    • If you want to reduce cross-region dependency,chooseRegional.
  4. If you chose regional, then select theRegion where you want tocreate your instance template.

  5. In theAvailability policies section, expandVM provisioning modeladvanced settings.

  6. Select theSet a time limit for the VM checkbox.

  7. In theTime limit type field, selectBy hours (default) tospecify the time limit as a duration. In the next field, enter theduration in hours.

  8. In theOn VM termination list, selectDelete.

  9. For the other fields, either accept the default values or modify them asrequired.

  10. ClickCreate.

gcloud

Use theinstance-templates create command.To automatically delete VMs after a specific duration, include the--max-run-duration flag and set the--instance-termination-action flag toDELETE as follows:

  gcloud compute instance-templates createINSTANCE_TEMPLATE_NAME \      --max-run-duration=DURATION \      --instance-termination-action=DELETE

Replace the following:

  • INSTANCE_TEMPLATE_NAME: the name of the instancetemplate.
  • DURATION: the duration you want the VMs to run.The MIG automatically deletes the VM after the specified duration.

    Format the duration as the number of days, hours, minutes, and secondsfollowed byd,h,m, ands respectively. For example, specify30m for a duration of 30 minutes, or specify1d2h3m4s for aduration of 1 day, 2 hours, 3 minutes, and 4 seconds. The minimumduration is 30 seconds (30s) and the maximum duration is 120 days(120d).

Terraform

To create an instance template using Terraform, use thegoogle_compute_instance_template resource.To create an instance template that automatically deletes VMs after aspecific duration, you must include themax_run_duration argument and set theinstance_termination_action argumenttoDELETE.

For more information, see theTerraform documentation for thegoogle_compute_instance_template resource.

REST

Use theinstanceTemplates.insert method.To automatically delete VMs after a specific duration, include themaxRunDuration field and set theinstanceTerminationAction field toDELETE as follows:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/instanceTemplates{  "name": "INSTANCE_TEMPLATE_NAME",  "properties": {    "machineType": "MACHINE_TYPE",    "networkInterfaces": [      {        "network": "global/networks/default",        "accessConfigs": [          {            "name": "external-IP",            "type": "ONE_TO_ONE_NAT"          }        ]      }    ],    "disks": [      {        "type": "PERSISTENT",        "boot": true,        "mode": "READ_WRITE",        "initializeParams":        {          "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"        }      }    ]    "scheduling": {      "maxRunDuration":      {        "seconds":DURATION      },      "instanceTerminationAction": "DELETE"    }  }}

Replace the following:

  • PROJECT_ID: theID of the projectin which you want to create the instance template.
  • INSTANCE_TEMPLATE_NAME: the name of the instancetemplate.
  • MACHINE_TYPE: thepredefinedorcustommachine type for the VMs in the group.
  • IMAGE_PROJECT: theimage projectthat contains the image; for example,debian-cloud.
  • IMAGE orIMAGE_FAMILY: specify oneof the following:

    • IMAGE: a specific version of the OS image; forexample,debian-10-buster-v20200309.

    • IMAGE_FAMILY: animage family. This specifies themost recent, non-deprecated OS image. For example, if you specifyfamily/debian-10, the latest version in the Debian 10 image familyis used.

  • DURATION: the duration you want the VMs to run.The MIG automatically deletes the VM after the specified duration.

    Format the duration as the number of days, hours, minutes, and secondsfollowed byd,h,m, ands respectively. For example, specify30m for a duration of 30 minutes, or specify1d2h3m4s for aduration of 1 day, 2 hours, 3 minutes, and 4 seconds. The minimumduration is 30 seconds (30s) and the maximum duration is 120 days(120d).

Create an instance template with a termination time for VMs

To automatically terminate VMs in a MIG at a specific time, set atermination time (terminationTime) in the instance template. You can set adate and time at which you want a MIG to terminate the VMs.

Console

  1. In the Google Cloud console, go to theInstance templates page.

    Go to Instance templates

  2. ClickCreate instance template.

  3. Select theLocation as follows:

    • If you want to use the instance template across regions,chooseGlobal.
    • If you want to reduce cross-region dependency,chooseRegional.
  4. If you chose regional, then select theRegion where you want tocreate your instance template.

  5. In theAvailability policies section, expandVM provisioning modeladvanced settings.

  6. In theTime limit type field, selectBy date to specify the timelimit as a time and date. In the next field, clickSelect date and time and select the date, time, and timezone for automatic termination.

  7. In theOn VM termination list, selectDelete.

  8. For the other fields, either accept the default values or modify them asrequired.

  9. ClickCreate.

gcloud

Use theinstance-templates create command.To automatically delete VMs at a specific time, include the--termination-time flag and set the--instance-termination-action flag toDELETE as follows:

  gcloud compute instance-templates createINSTANCE_TEMPLATE_NAME \      --termination-time=TIME \      --instance-termination-action=DELETE

Replace the following:

  • INSTANCE_TEMPLATE_NAME: the name of the instancetemplate.
  • TIME: the time you want this VMto be automatically terminated. The time you specify must be at least 30seconds in the future and at most 120 days in the future. Format the timeas aRFC 3339 timestamp:

    YYYY-MM-DDTHH:MM:SSOFFSET

    Replace the following:

    • YYYY-MM-DD: A date formatted as a 4-digit year,2-digit month, and 2-digit day of the month separated by hyphens.
    • HH:MM:SS: A time formatted as a 2-digit hourusing 24-hour time, 2-digit minute, and 2-digit secondseparated by colons.
    • OFFSET: The time zone formatted as an offsetof Coordinated Universal Time (UTC). For example, to usePacific Standard Time (PST), which is 8 hours earlier than UTC, specify-08:00. Alternatively, to use no offset (UTC+0), specifyZ.

REST

Use theinstanceTemplates.insert method.To automatically delete VMs at a specific time, include theterminationTime field and set theinstanceTerminationAction field toDELETE as follows:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/instanceTemplates{  "name": "INSTANCE_TEMPLATE_NAME",  "properties": {    "machineType": "MACHINE_TYPE",    "networkInterfaces": [      {        "network": "global/networks/default",        "accessConfigs": [          {            "name": "external-IP",            "type": "ONE_TO_ONE_NAT"          }        ]      }    ],    "disks": [      {        "type": "PERSISTENT",        "boot": true,        "mode": "READ_WRITE",        "initializeParams":        {          "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"        }      }    ]    "scheduling": {      "terminationTime":TIME,      "instanceTerminationAction": "DELETE"    }  }}

Replace the following:

  • PROJECT_ID: theID of the projectin which you want to create the instance template.
  • INSTANCE_TEMPLATE_NAME: the name of the instancetemplate.
  • MACHINE_TYPE: thepredefinedorcustommachine type for the VMs in the group.
  • IMAGE_PROJECT: theimage projectthat contains the image; for example,debian-cloud.
  • IMAGE orIMAGE_FAMILY: specify oneof the following:

    • IMAGE: a specific version of the OS image; forexample,debian-10-buster-v20200309.

    • IMAGE_FAMILY: animage family. This specifies themost recent, non-deprecated OS image. For example, if you specifyfamily/debian-10, the latest version in the Debian 10 image familyis used.

  • TIME: The time you want this VMto be automatically terminated. The time you specify must be at least 30seconds in the future and at most 120 days in the future. Format the timeas aRFC 3339 timestamp:

    YYYY-MM-DDTHH:MM:SSOFFSET

    Replace the following:

    • YYYY-MM-DD: A date formatted as a 4-digit year,2-digit month, and 2-digit day of the month separated by hyphens.
    • HH:MM:SS: A time formatted as a 2-digit hourusing 24-hour time, 2-digit minute, and 2-digit secondseparated by colons.
    • OFFSET: The time zone formatted as an offsetof Coordinated Universal Time (UTC). For example, to usePacific Standard Time (PST), which is 8 hours earlier than UTC, specify-08:00. Alternatively, to use no offset (UTC+0), specifyZ.

How time limit works for VMs in a MIG

When you specify a time limit for VMs in a MIG, the time at which a MIGwill terminate a VM is automatically set in the termination timestamp(terminationTimestamp) field of the VM.

Based on the type of time limit that you specify, the termination timestamp of aVM is set as follows:

  • Time limit as a run duration (maxRunDuration):

    terminationTimestamp of a VM = VM's latest creation or start time +maxRunDuration

    When you specify a duration, the termination timestamp is set relative tothe VM's latest creation or start time. If the VM is recreated, restarted,resumed, or replaced, then the termination timestamp is recalculated. Theterminationtimestamp can vary across the VMs in a MIG based on the time that each VMwas last created or started. For example, if a VM is repaired, thetermination timestamp of the VM is recalculated by adding the duration tothe time the VM was recreated during the repair.

  • Time limit as a termination time (terminationTime):

    terminationTimestamp of a VM =terminationTime

    When you specify a time, the termination timestamp is set to that time,provided the time is in the future. If the termination time has passed, anyMIG action that attempts to create, restart, or replace a VM fails withanerror.To resolve such an error, you must create a new instance templatewith a termination time in the future and apply that template to the MIG. Ifyou want to use the existing template properties in the new template, thencreate an instance template based on the existing template.

During a VM refresh, the termination timestamp doesn't change. For example,if you set thedisruption levelfor updates toREFRESH, then the termination timestamp is retainedwhenever the MIG updates the VM.

When yoususpend or stopa VM in a MIG, the termination timestamp is automatically cleared irrespectiveof the type of time limit. When you resume or start a VM, the terminationtimestamp is set again based on the type of time limit as explained earlier in thissection.

How autoscaling works when a time limit is set

Autoscaling lets your MIG automatically add or remove VMs based on increasesor decreases in load. When a MIG deletes VMs that have reached their terminationtimestamps, the MIG creates new VMs to maintain therecommended size by theautoscaler. The new VMs run for the specified time limit. If the autoscalerrecommendation is to reduce the number of VMs, then the MIG deletes VMs evenbefore they reach their time limits.

If you've configuredscaling schedules,the VMs run only until the end of a schedule or until a VM reaches itstermination timestamp, whichever comes first.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.