Create a Compute Engine managed instance group with schedule-based autoscaling

Use Terraform to create a Compute Engine managed instance group (MIG) with schedule-based autoscaling.

Code sample

Terraform

To learn how to apply or remove a Terraform configuration, see Basic Terraform commands. For more information, see the Terraform provider reference documentation.

resource "google_compute_autoscaler" "default" {
  provider = google-beta
  name     = "my-autoscaler"
  zone     = "us-central1-f"
  target   = google_compute_instance_group_manager.default.id

  autoscaling_policy {
    max_replicas    = 5
    min_replicas    = 1
    cooldown_period = 60

    scaling_schedules {
      name                  = "every-weekday-morning"
      description           = "Increase to 2 every weekday at 7AM for 12 hours."
      min_required_replicas = 2
      schedule              = "0 7 * * MON-FRI"
      time_zone             = "America/New_York"
      duration_sec          = 43200
    }
  }
}

resource "google_compute_instance_template" "default" {
  name           = "my-instance-template"
  machine_type   = "e2-medium"
  can_ip_forward = false

  tags = ["tag1", "tag2"]

  disk {
    source_image = data.google_compute_image.debian_11.id
  }

  network_interface {
    network = "default"
  }

  metadata = {
    name = "value"
  }

  service_account {
    scopes = ["userinfo-email", "compute-ro", "storage-ro"]
  }
}


resource "google_compute_instance_group_manager" "default" {

  name = "my-igm"
  zone = "us-central1-f"

  version {
    instance_template = google_compute_instance_template.default.id
    name              = "primary"
  }

  base_instance_name = "autoscaler-sample"
}

data "google_compute_image" "debian_11" {

  family  = "debian-11"
  project = "debian-cloud"
}

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.